TopMenu

Managing Cross Cutting Concerns – Logging

Cross cutting concerns (a.k.a Aspects) are part of each every project built or being built and so called the Infrastructure. A quick definition of CCC (Cross cutting concerns), An essential part of software application that cuts across the layers of the application. CCC can including things like Logging, Exception/Error Handling, Caching, Monitoring, Security, Communication etc. and there’s a list of operation that are integral part of an application and needs to be performed across the layers. Take a look at a layered application architecture. It has DataLayer, BusinessLayer and UI or Presentation Layer. Those usually managed separately in individual projects but what kept me thinking is the way to manage the cross cutting. The challenge comes with the fact that CCC is shared across the layer. It can make maintenance of an application a nightmare if not implemented correctly.

image

In this post we’ll be looking at the pain areas and possible solution for better implementation of CCC but we’ll discuss a type of Aspect of an application architecture in Cross cutting concern, a set of sample problems and what can be best practices to avoid them etc. Unlike Java in C# Aspect oriented programming (AOP) is not fully supported. Using Aspects (Attributes in C#) is one way of introducing Cross cutting concerns in an application. But that’s a topic that we’ll discuss later in this post.

The problem

To depict the idea of the problem let’s start with simplest things known as Logging in CCC. Let’s talk about the logging aspect in an application from the various developer’s point of view. There could be possible cases during application development:

Case 1: Developer didn’t care about it unless….

This is the least and last thing that I’ve seen people care about unless the application is ready for Production or it’s already in production and bugs/problems are reported from the end users. Then the developer realized the importance of logs (Logging) and the whole picture gets clear dictating importance and necessity of logging in application. What happened during development could be:

1. Least or almost no logging.

2. Resulting in hot patch in production with minimum logging support. (Too much risk)

3. Consequence of #1 and #2 resulting in last moment code changes and endup with hard coded trace/log statement at random places.

Case 2: Developer cared about it too much

In this case developer knows the importance of logging in each layer and logs messages and any critical things that could happen in application. But usually end up in situations like:

  1. Methods are cluttered with logging statements. A case of violation of SRP(Single Responsibility Principle).
    try
    {
    // some operations here.
    }
    catch (Exception ex)
    {
    this.logger.Log(ex);
    throw;
    }

  2. Too much usage of Try..catch almost used in each function. A case of violation of DRY principle.(Don’t Repeat Yourself) .
  3. Too much logging.
Case 3: The optimistic developer

This is a case when developer have knowledge of not overflooding the code with log statement and she is also concerned about managing the Cross cutting across components. But she might get confused with the way to manage it having options available like:


  1. A static logger factory to provide logger instance access.
    public class MyController : BaseController
    {
    private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

    public IList<Customers> Get()
    {
    Logger.Debug("Done! I can use it!");
    }
    }

  2. Adding logger property in every class via property or constructor injection and using DI container to inject the logger.
    public class MyController
    {
    private readonly ILog _logger;

    public MyController(ILog logger)
    {
    _logger = logger;
    }

    public IList<Customers> Get()
    {
    _logger.Debug("I am injected via constructor using some IoC!");
    }
    }

  3. Use AOP (Aspect oriented programming).

Now we all must have seen these cases or must felt somewhere by ourself somewhere in our career phase. Now let’s talk about the possible solutions to avoid such situations.

Solution approach[Case1]

This situation can be avoided by Design. Why the developer failed or didn’t care about the logging is because the design didn’t had enough support for Infrastructure in early stage of development. If they failed to incorporate cross cutting it wasn’t developer’s fault at all. It was the vague design of application.

To visualize it in real life scenario, let’s think of a building at construction site. If design doesn’t include the Hoses, Vent, Electricity wiring pipes, Windows etc. then later things might end-up breaking into walls and ceilings to get those small but necessary setups done. This is exactly what happens with software applications; end-up plumbing those cross cutting concerns later on. Situations like this are surely not a good sign.

Introduce a solid infrastructure in early designing phase before development starts. Cross cuttings concerns should be well defined. Infrastructure components which are required on an individual layer should be available by design.

E.g. On a business layer side a base class can have access to a logger factory or logger instance that can be accessed for logging purpose in all derived classes.

public abstract class BaseCommand
{
protected ILogger Logger { get; private set; }

public BaseCommand()
{
Logger = NullLogger.Instance;
}

public BaseCommand(ILogger logger)
{
Logger = logger;
}
}
Now let’s discuss few aspects of above design:

1. Logger in base class would be a good place why? because this piece of information can be shared to all derived classes.

2. Default instance can have a Null logger so it’s not a dependency any more. A system should work without an Aspect like logging. It’s shouldn’t be a defined as dependency in your application design.

3. Now Developer doesn’t have to worry about introducing logging by herself in first place.

This might not be a perfect example but this is “a way” of putting infrastructure/cross cutting concerns in right place at right time.

Solution Approach[Case 2]

Which in short says, Logging aspect viz. Infrastructure component is used but not correctly, sample shown above in problem Case 2. Defining “What and When to log” is very important. This is again should be defined in early stage of development. Areas that should be addressed on individual Layer are: What application should log on individual layer? E.g. Error, Exception (Handled/Unhandled), Trace info etc. along with which information must be shared across the layers.

The case of exception handling is very common that required logging to be done and exception would be wrapped and sent to another layer. In this case:

1. Design should manage a sample case like error handling at common places. So that logging can be performed without duplication and without avoiding SRP.

Let’s take an example of OrderProcessorCommand that processes an order this will be inherited from our above defined BaseCommand.

public class OrderProcessorCommand : BaseCommand
{
public void Execute(Order order)
{
try
{
// Business logic for processing order
}
catch(InvalidOperationException exception)
{
Logger.LogError(string.Format("Invalid operation.Order {0}", order.OrderId, exception));
}
}
}
Think of 10 more commands like this and may be in future you require to create more commands mean more try..catch and logging statements cluttered in your application. Now let’s redesign the above classes.

Let’s start with extending BaseCommandClass.

public abstract class BaseCommand<T>
{
protected ILogger Logger { get; private set; }

public BaseCommand()
{
Logger = NullLogger.Instance;
}

public BaseCommand(ILogger logger)
{
Logger = logger;
}

public void Execute(T parameter)
{
try
{
CheckForNull(parameter); // common place for command parameter null checking :)

ExecuteCore(parameter);
}
catch (InvalidOperationException exception) // gotcha! that's it handling all common commands errors here.
{
HandleError(exception.Message, exception);
}
}

protected abstract void ExecuteCore(T Parameter);

protected virtual void HandleError(string message, Exception exception)
{
// Do more with logging.
Logger.LogError(message, exception);
}

private void CheckForNull(T parameter)
{
if(parameter == null)
{
throw new ArgumentNullException("Command parameter should not be null.");
}
}
}
Now the base class is equipped with more infrastructure support i.e. Error/Exception handling. Now the OrderProcessorCommand will look like this:
public class OrderProcessorCommand : BaseCommand<Order>
{
protected override void ExecuteCore(Order Parameter)
{
// Business logic for processing order
}
}
Neat!! Isn’t it? More over if any particular command required to handle its exception in its own way then the new design is supporting it very well. E.g. the occurred exception has to be wrapped and should be sent to another layer.
public class UpdateOrderCommand : BaseCommand<Order>
{
protected override void ExecuteCore(Order Parameter)
{
// Business logic for processing order
}

protected override void HandleError(string message, Exception exception)
{
// Let the logging done in first place.
base.HandleError(message, exception);

// For demo purpose only. In real scenario error codes can be used here.
if (exception.GetType() == typeof(InvalidOperationException))
{
// Now pack it and tag it.
throw new InvalidOrderException("The order has invalid items.");
}
}
}
As you can see we have removed the clutter of logging and exception handling at one place. You can imagine how neat your all command classes would look like.

Conclusion, A better design in application can provide much better way to manage and clean the Cross cutting concerns clutter. This is why Design patterns are important during development.

Solution Approach[Case3]

Now this case is really interesting. In this case developer knows the problems and keeps the infrastructure (CCC) stuff usage straight and clean in the application by following best practices. But again during those practices another question comes in mind about managing the objects and classes for infrastructure components or aspects like Logging. This is really a topic where individuals have their own opinions and all are interesting you can’t deny one straightforward. After researching and with all experience I had so far with Cross cuttings (logging for example in this blog post) following can be best practices (IMO):

1. Infrastructure components like Logger shouldn’t be considered as Dependencies. Though one can use constructor injection but make sure it doesn’t become the “required” component. Application should work even without logger.

2. Singletons or Static logger factories are good to keep for shared instances. You should keep the infrastructure (CCC) stuff as thin as possible.

3. If you’re using Dependency injection. Logger object shouldn’t be registered with “Transient” life cycle.

4. Usage of AOP(Aspect oriented programming) for infrastructure (CCC) is really interesting one specially in C#. Found a definition of AOP which says,

"Aspect Oriented Programming is a methodology to separate cross cut code across different modules in a software system."

Means thinking of using AOP is not a false alarm at all. Unfortunately AOP is not fully supported in C#. C# supports Attributes but defining attributes isn’t enough a supporting actor class required to perform respective actions.

E.g. Logging can be done using AOP. Castle.Dynamic provides interceptors that can be used to intercept the method invocation for logging.

[EnableLogging]
protected override void ExecuteCore(Order Parameter)
{
// Business logic for processing order
}
Ayende has written a very informative article on logging via AOP. But using run time interceptors like Castle.DynamicProxy has their own runtime cost. As it works based on run time Proxy wrapper generation of each marked method/class. IMO this is too much cost for operations like Logging. You may not want to hamper the performance of your application just because of Logger operations. Look at the more types of approaches to achieve AOP in .Net.

But surely this can be a great way to incorporate cross cuttings in your application if done via Compile Time weaving or Link Time weaving. Let’s not go more deep about the AOP here. I’ll be writing another post details AOP possibilities in .Net C# separately.

Conclusion

Although Cross Cuttings Concerns are not sometimes not considered major part of an application. Often they appear in Application architecture design diagram nicely but in application code it remains less important (Observed many instances in couple of project I looked upon). Cross cuttings are the infrastructure on which great applications are built. And their importance is as equal as any of the concrete layer in application architecture. This blog post mostly talked about Logging. The problems I addressed here for a small aspect like loggin are real and often observed in development phase of application.
image

I’ll be writing more about other cross cutting concerns like Security/Error handling but let’s wrap things up here.

Hope you like this post. Kindly share/like if it really helped you by improvising your thoughts over CCC.

Setting up SSL encryption to WCF REST API Service

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Securing basic authentication credentials using SSL over Http i.e. (Https)

The Basic authentication information is usually sent in plain text (encrypted by Base64 string which can be easily decrypted) over the network. Most of the browsers issue a warning about this secure information being sent as plain text. If you try to launch the API call in IE browser you’ll see a warning something like below:

clip_image002

Here comes the Transport layer security into picture. All communication being done over the network can be secured using the Transport layer security by using SSL(Secure Sockets Layer) certificates.
To apply SSL security first you need a certificate. In order to get a real certificate one can go to certificates providers like Thawte, digicert, Godaddy etc. and purchase a certificate. These providers (not mentioning any specific provider but all in general) are trusted providers for issuing digital certificates to ensure that identity of certificate owner is verified.

But in development environment you don’t need to purchase a SSL certificate in real. You can generate a local self-signed certificate from your machine. But the certificate would be only valid for your local use only. If you use the certificate over the network this would be invalidated. I’m not going into details so let’s get started how to get a self-signed server certificate that you can use in development environment.

Creating a certificate and enabling the Https settings to use the certificate

You have two options either create a certificate using ‘makecert’ command. Here’s a nice detailed article with quite good explanation about certificates. Or you can use IIS 7.0 or greater to create your certificate.

1. Launch Internet Manager from control panel or goto Run -> type ‘Inetmgr’ -> press enter.

2. Select the ROOT node on left side panel. Look for `Server Certificates` under `IIS` on right panel.

clip_image002

3. Double click on ‘Server Certificates’ and select ‘Create self-signed certificate’.

image

4. Now enter the name of certificate. This will be the friendly name of your certificate.

clip_image006

5. Click Ok and certificate that you have created would appear in parent window.

6. Now select the website you want to configure for HTTPS in IIS.

clip_image008

7. In the Site Bindings window, click Add.

clip_image009

8. In the Add Site Binding window, enter the following information:

Type:

In the drop-down list, select https.

IP address:

In the drop-down list, select All Unassigned.

Port:

Enter 443. The port for SSL traffic is usually port 443.

SSL certificate:

In the drop-down list, select your recently imported SSL Certificate by its friendly name.

clip_image010

9. Click OK. Your SSL Certificate is now installed and the website is configured to accept secure connections.

Note: You may have to restart IIS or the server for it to recognize the new certificate (in some cases).

10. To test the setting open the site binding again and select Https binding and click on ‘Browser’. You might see below error.

clip_image012

11. To get rid of this error use the machine name exactly same as your certificate section “Issued to” says. E.g. If you open your certificate then you’ll see issued to property and which should be your Machine name. If your machine is part of a domain then machine name would be like <machinename>.<xyz>.<domain> etc. so if you open it in your browser will fully qualified name of your machine then you won’t be getting that error.

clip_image014

Setting up WCF REST service to use SSL (Https)

To enable the SSL over Http protocol follow below steps:

1. Add Protocol mapping for the webhttpbinding to use https.

<protocolMapping>
<add binding="webHttpBinding" scheme="https"/>
</protocolMapping>
2. Under binding -> webhttpbindings enable security mode Transport.
<bindings>
<webHttpBinding>
<security mode="Transport" />
</binding>
</webHttpBinding>
</bindings>
3. Add a host base address under services -> service.
<service name="WcfWebHttpIISHostingSample.TestService" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="https://desktop-pc.mydomain/WcfWebHttpIISHostingSample/api/"/>
</baseAddresses>
</host>


</services>
4. Now rebuild the service and test it in the browser. You will not see the warning of in-secure server communication any more.

clip_image015

I hope this series of WCF REST API tutorial will help you. Feel free to like and share. The complete sample used in this Guide can be found here on Github.

Download the complete tutorial Guide as PDF from here.

Basic Authentication in WCF REST on IIS

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Adding Basic authentication

The REST services are built and run over http protocol. A simple way to enable the authentication is to use Basic Authentication(i.e. user/pwd). Basic authentication can be enabled over http protocol. Now here are the choices that we have:

We can use simple transport level basic authentication by using Custom username and password validator as mentioned here. But the author has explicitly stated that this will only work in self hosted environment. Which is not our case as we are using IIS to host our service. Also there are other method available on the internet like by extending ServiceAuthenticationManager or using a custom MessageInspector and use it like a custom user/pwd validator but I was not really convinced with those methods because somehow they were not best candidate for our scenario. The challenge comes with IIS is that IIS does the authentication before WCF receives the request. And Till now there’s no out of the box support for Basic Authentication for WCF REST on IIS. So we have to go with our custom solution which is by extending ServiceAuthorizationManager class and override method CheckAccessCore and using it in Service Behaviors as default Authorization manager. The configuration would look something like below after setting up a custom service Authorization manager.

      <serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization
serviceAuthorizationManagerType
=" WcfWebHttpIISHostingSample.RestAuthorizationManager, WcfWebHttpIISHostingSample"/>
</behavior>
</serviceBehaviors>
Now I have to extend the class ServiceAuthorizationManager with a custom class RestAuthorizationManager which I named it to make sense with the context.
   public class RestAuthorizationManager : ServiceAuthorizationManager
{
/// <summary>
/// Method source sample taken from here: http://bit.ly/1hUa1LR
/// </summary>
protected override bool CheckAccessCore(OperationContext operationContext)
{
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if ((authHeader != null) && (authHeader != string.Empty))
{
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };
if ((user.Name == "testuser" && user.Password == "testpassword"))
{
//User is authrized and originating call will proceed
return true;
}
else
{
//not authorized
return false;
}
}
else
{
//No authorization header was provided, so challenge the client to provide before proceeding:
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"MyWCFService\"");
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
}
Now your application is ready to challenge any request with Basic Authentication. To test it you can use any client like Fiddler or Chrome’s post man plugin and see what outcome you get. Let’s simply make a request from normal browser, I’ll get a challenge for basic authentication prompting user/password.

clip_image002

Enter the username - testuser and password – testpassword which we have used to validate the values in our RestAuthorizationManager class.

clip_image004

Continue to – Using Https and SSL to encrypt the Basic authentication information, Creating a self signed certificate and Setup IIS and configure WCF REST Service.


Or Download the complete tutorial Guide as PDF from here.

Compiling C# 6.0 code using Roslyn Microsoft.CodeAnalysis v1.0.0 Programmatically

Since the release of recent release of Roslyn aka Microsoft.CodeAnlysis all the article and blogs on internet which were written using Alpha\Beta version of Roslyn are now out dated.
Recently I wanted to write a program using latest stable version (v1.0.0) of Roslyn to compile the CSharp6 versioned code against .Net 4.6 framework. In old beta version there was no option for specifying Target framework and compiler RunTime or maybe I missed it somehow. So I was wondering how to achieve in latest release. I tried searching internet, stackoverflow but finally I end reading and comparing old methods to new and renamed methods and finally created a working sample.

Roslyn Version – Microsoft.CodeAnalysis version="1.0.0"

Install it from Nuget:

> Install-Package Microsoft.CodeAnalysis -Version 1.0.0

Sharing my initial observations of this encounter:

1. Roslyn have become more extensible.

2. Less dependency on the platform version on Roslyn based utilities.

3. The problem was with one package “Microsoft.Workspaces.Desktop” which failed by build because this library requires 4.5.2 or latest .Net version 4.6. So I had to install 4.6 to make it working.

4. Now you can specify almost everything required for customized compilation.

Here’s my complete program. This is a console application that compile a csharp file to Dll. The latest functions in Roslyn have options to supply more information e.g. which platform you want to use for Compilation and what compilation or language version you want to use.

public class Program
{
private static readonly IEnumerable<string> DefaultNamespaces =
new[]
{
"System",
"System.IO",
"System.Net",
"System.Linq",
"System.Text",
"System.Text.RegularExpressions",
"System.Collections.Generic"
};

private static string runtimePath = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\{0}.dll";

private static readonly IEnumerable<MetadataReference> DefaultReferences =
new[]
{
MetadataReference.CreateFromFile(string.Format(runtimePath, "mscorlib")),
MetadataReference.CreateFromFile(string.Format(runtimePath, "System")),
MetadataReference.CreateFromFile(string.Format(runtimePath, "System.Core"))
};

private static readonly CSharpCompilationOptions DefaultCompilationOptions =
new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication)
.WithOverflowChecks(true)
.WithOptimizationLevel(OptimizationLevel.Release)
.WithUsings(DefaultNamespaces);

public static SyntaxTree Parse(string text, string filename = "", CSharpParseOptions options = null)
{
var stringText = SourceText.From(text, Encoding.UTF8);
return SyntaxFactory.ParseSyntaxTree(stringText, options, filename);
}

public static void Main(string[] args)
{
var fileToCompile = @"C:\Users\....\Documents\Visual Studio 2013\Projects\ConsoleForEverything\SignalR_Everything\Program.cs";
var source = File.ReadAllText(fileToCompile);
var parsedSyntaxTree = Parse(source, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));

var compilation
= CSharpCompilation.Create("Test.dll", new SyntaxTree[] { parsedSyntaxTree }, DefaultReferences, DefaultCompilationOptions);
try
{
var result = compilation.Emit(@"c:\temp\Test.dll");

Console.WriteLine(result.Success ? "Sucess!!" : "Failed");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}
}
Although this program could have been much better with all refactoring and organizing but this will give you a kick start.

The new Code Analyzer and CSharp syntax rewriters are more interesting things and are on my list to explore.

Hosting WCF REST service in IIS

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Hosting and Deploying a WCF REST service in IIS

To Host the above service in IIS follow below steps:
1. Right click on the project and go to Properties. In properties window select Web.
2. Now under Servers on Web settings you’ll see following details change the “IIS Express” to “IIS Server”.

clip_image002

3. Now Click on Create Virtual Directory. Now if you have Visual Studio running As Administrator then you’ll get a message The Virtual directory was created successfully! Otherwise you’ll receive an error message and you need to launch again Visual studio as Administrator. I mentioned it in the start of this Guide.

4. Now press F5 and your website will be up and running on IIS server instead of your IIS express.

clip_image003


Deploying a WCF REST service on IIS Local machine (optional)

(Optional) You don’t actually need to deploy the current WCF service because the visual studio already using IIS server for hosting as detailed in above step. This is just to let you know how to deploy a WCF REST service on IIS.
Follow below steps:
1. Right click on Project -> Goto Publish.

image

2. In Publish windows open the dropdown for profiles and select New Profile.

image

3. Select publish method as “Web Deploy”. Enter server as “Localhost”. Add site name as “Default Web site/WcfWebHttpIISHostingSample_Demo2”. Click Validate connection it’ll verify access rights and other information provided.

SNAGHTMLc4aa1c7

4. Once the Validate connection succeeds click publish. You’ll get the success message in output window in Visual studio.

5. Test the service by entering in browser following url - http://localhost/WcfWebHttpIISHostingSample_Demo2/Data/TestingDeploymentSuccess

Continue reading - Adding security to the WCF REST service using custom Basic Authentication

Or Download the complete tutorial Guide as PDF from here.

Securing WCF REST API using SSL and Basic Authentication

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Creating a WCF REST API service

To get started quickly we’ll be using the default template of WCF service library provided in Visual studio 2013 which I’m going to use in this guide. Follow the steps below:

1. Launch visual studio 2013(choose “Run as Administrator”, we’ll see later why?)
2. From Menu File -> New -> Project. or click on Start Page to start a New Project. clip_image002
3. Let’s name it as WcfWebHttpIISHostingSample Now you’ll see couple of files already added to the Wcf Service project.
clip_image003 
4. Delete IService1.cs and Service1.svc file as we’ll be creating new files and use our code to host the service via ServiceHostFactory class.

5. Add a new interface ITestService by right click on project and Add new item -> select Interface and rename it to ITestService. Copy below code and add it in newly created interface.

namespace WcfWebHttpIISHostingSample
{
[ServiceContract]
public interface ITestService
{
[WebInvoke(Method = "GET", UriTemplate = "/Data/{data}")]
string GetData(string data);
}
}
In above interface we have added WebInvoke attribute though we can also use WebGet it would not make any difference. I’ll stick with WebInvoke as it support POST, PUT, DELETE http verbs as well.

6. Add a new class TestService which will implement the above declared interface.

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;

namespace WcfWebHttpIISHostingSample
{
[ServiceContract]
public interface ITestService
{
[WebInvoke(Method = "GET", UriTemplate = "/Data/{data}")]
string GetData(string data);
}
}
7. We have defined a service contract, a Rest method with a sample definition. Now we have to define its end points. To add end point simply copy below settings and paste it into your configuration file(web.config) of newly created project file under service.model tag.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpServiceBehavior">
<!-- Important this is the behavior that makes a normal WCF service to REST based service-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfWebHttpIISHostingSample.TestService" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost/WCFRestAuthentication/api/"/>
</baseAddresses>
</host>
<endpoint binding="webHttpBinding" contract="WcfWebHttpIISHostingSample.ITestService" behaviorConfiguration="webHttpServiceBehavior"/>
</service>
</services>
</system.serviceModel>
8. Now we have an end point. So Next we’ll add a service host factory that will host the service in IISExpress or Local development server at this moment.

9. Add new item Global.asax and add following code in Application_Start method. You can find it Under New Item -> Web -> Global application Handler.

protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(TestService)));
}
10. Now you’ll be getting an error on ServiceRoute class in above code. To remove this error we have to add a new reference from Add reference -> Assemblies -> System.Model.Activation. And the error will be gone.
11. Now right click on Project and go to Properties. In properties window select Web and Add specific page details to map the service operation that we defined on our contract. Add Data/HelloWorldTestData in Specific page setting. Here Data is your path of operation that we have defined in WebInvoke attribute and “HelloWorldTestData” is your argument that the service method will receive as argument. See below:

clip_image004

12. Save All and Press F5.

clip_image006 
If you see a web page like this means you have successfully created a WCF REST service.

Continue to - Hosting and Deploying a WCF REST service in IIS
Download the complete tutorial Guide as PDF from here.

WCF REST API CORS enabled extension

The REST Apis are designed to work with Web i.e. a network of different connect domain that works together by sharing resources. But in today’s world we have all modern browsers which are highly supporting the CORS. Those who don’t know about CORS can learn about it here.

In a simple language, CORS is simply allowing other domain to request for a resource hosted in a another domain. So e.g. If a image is hosted on SiteA.com and Siteb.com wants to access this image to display in one of his page then SiteA.com has to allow it. The browser which is accessing SiteB.com will know by reading the response header which are coming after making a request to SiteA.com. So if it has CORS header information then the request can be fetcher other wise browser will simply reject the response without displaying any specific error.

Sample Response headers of CORS from SiteA.com:
Access-Control-Allow-Origin: http://SiteB.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000

You visualize the above situation something like below though it’s not a complete coverage of whole CORS concept but it will get you going.
Example with NO CORS

Example with CORS support

Know more about the Server side CORS and Client CORS. The  same scenario applies when a cross domain REST Api request is made. So Your WCF REST api service should server the response with CORS headers. The feature is not supported out of box but WCF provides a lot of extensibility points. So you can extend/create a new behavior and plug it in to have your WCF REST Api CORS enabled.
So conceptually you can develop a new Endpoint behaviorEndpoint behavior with a custom message inspectormessage inspector that will inject the CORS headers settings in the Response you’re the requesting browser doesn’t deny it.
Here’s how the custom message inspector would look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
 
namespace WebHttpBehaviorExtensions.Cors
{
    public class CustomHeaderMessageInspector : IDispatchMessageInspector
    {
        Dictionary<string, string> requiredHeaders;
        public CustomHeaderMessageInspector(Dictionary<string, string> headers)
        {
            requiredHeaders = headers ?? new Dictionary<string, string>();
        }
 
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            return null;
        }
 
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
            foreach (var item in requiredHeaders)
            {
                httpHeader.Headers.Add(item.Key, item.Value);
            }
        }
    }
}



Message inspector is actually that adds the headers into response with method BeforeSendReply. Now we have to inject this custom message inspector object into collection of default message inspector. To do that we have create a new class implementing IEndpointBehavior interface also we’ll be using the same class to extend the base class BehaviorExtensionElement(This would help injecting the behavior from configuration.)



using System;
using System.Collections.Generic;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
 
namespace WebHttpBehaviorExtensions.Cors
{
    class EnableCorsBehavior : BehaviorExtensionElement, IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        { }
 
        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        { }
 
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            var requiredHeaders = new Dictionary<string, string>();
 
            requiredHeaders.Add("Access-Control-Allow-Origin", "*");
            requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
            requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
 
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
        }
 
        public void Validate(ServiceEndpoint endpoint) { }
 
        public override Type BehaviorType
        {
            get { return typeof(EnableCorsBehavior); }
        }
 
        protected override object CreateBehavior()
        {
            return new EnableCorsBehavior();
        }
    }
}


That’s it. Now to show you the configuration settings I’ll just put the parts which are needs to be updated with this new behavior setting. In configuration under <service.model> add following endpoint behavior:
Define the Extension behavior first


<extensions>
      <behaviorExtensions>
        <add name="corsBehavior" type="WebHttpBehaviorExtensions.Cors.EnableCorsBehavior, WebHttpBehaviorExtensions, Version=1.0.0.0, Culture=neutral" />
      </behaviorExtensions>
</extensions>

Add behavior


<behaviors>
     <endpointBehaviors>
       <behavior name="webHttpServiceBehavior">
         <corsBehavior />
         <webHttp/>
       </behavior>
     </endpointBehaviors>
</behaviors>
Now add the custom behavior settings to your endpoint in <services> section:


<services>
  <service name="WcfWebHttpIISHostingSample.TestService" behaviorConfiguration="ServiceBehavior">
    <endpoint binding="webHttpBinding" contract="WcfWebHttpIISHostingSample.ITestService" behaviorConfiguration="webHttpServiceBehavior" />
  </service>
</services>

That’s it. Now you can test your settings by deploying the WCF REST service to IIS and when making a request press F12 and look for Network request and response Headers. You can also use tools like `Fiddler` and `Chrome Post Master` to perform a Get/Post request and analyzing header.

This blog post is part of a Extension behavior library that I’m currently working on to provide a set of Regularly required feature which aren’t available out of the box. To download the Library via Nuget from here:
Download WebHttpBehaviorExtension Nuget

If you like to contribute or want to look at the source code. The complete source code is open source and hosted on Github.
image