Archive

Archive for the ‘OWIN’ Category

Testing Web API

July 31, 2015 3 comments

Continuing with my previous post on Implementing Web API Versioning using OWIN, in this post I am going to show how to write unit test for your Web APIs.

As we know that the beauty of OWIN is able to run your web application independent of the web server and based on this principle the Microsoft.Owin.Testing takes advantage of this feature to host the Web API in memory and execute the methods. Very simple and straight forward.

Lets get started by creating a new Unit Test project in Visual Studio and get the Microsft.Owin.Testing package from the Nuget Server as shown below.

PM> Install-Package Microsoft.Owin.Testing

Next step is to create a custom Startup class and bring in any services or OWIN Middleware which our Web API depends upon. As this is a demo Web API application I will just configure the DefaultVersionSelector we build in the previous post.

CustomStartup.cs

public class CustomStartup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new
            {
                id = RouteParameter.Optional,
                version = "1"
            });

        config.Services.Replace(
            typeof(IHttpControllerSelector),
            new DefaultVersionControllerSelector(
                config,
                new DefaultVersionSelector()));
        app.UseWebApi(config);
    }
}

As you can see nothing special in the startup class it is identical to our Web API project startup class and all I am doing is registering my DefaultVersionSelector and it dependencies and asking the IAppBuilder to invoke the OWIN Web API Middleware.

Now we are going to write a unit test which will use the OWIN testing component and invoke a simple get on our values controller.

WhenUsingOwinTestServer.cs

public class WhenUsingOwinTestServer
{
    private const string ContentTypeJsonVersion1 = "application/json;version=1";

    private const string AcceptHeader = "Accept";

    private const string RequestUri = "/api/values";

    private const string ExpectValueVersion1 = "[\"value1-Version1\",\"value2-version1\"]";


    [TestMethod]
    public void ShouldBeAbleToGetResultForVersion1()
    {
        using (var server = TestServer.Create<CustomStartup>())
        {
            var client = server.HttpClient;

            client.DefaultRequestHeaders.Add(AcceptHeader, ContentTypeJsonVersion1);
            var task = server.HttpClient.GetAsync(RequestUri);
            var response = task.Result.Content.ReadAsStringAsync();
            Assert.AreEqual(ExpectValueVersion1, response.Result);
        }
    }
}

As you can see in the above code we are using the TestServer to host Web API with our custom startup class. First we get a reference of the it’s HttpClient object and add our accept header with the versioning information. Next we make a GET request at the api/values end point,as everything is happening in memory you can see we don’t specify the web server in our URI.

Rest is pretty straight forward and we assert that the expected values and the results do match.

Advertisements

Implementing Web API Versioning using OWIN

June 30, 2015 3 comments

In my previous post "Designing Web API Versioning" I covered some of the design aspects of versioning and in this post I am going to show you how to implement versioning in Web APIs using OWIN.

First I am going to define a simple interface so that we can plug this in the OWIN Pipeline and it allows a nice separation of Concerns and promotes Single Responsibility principle.

IVersionSelector.cs

public interface IVersionSelector
{
    string GetVersion(HttpRequestMessage request, IHttpRoute route);
}

As you can see the interface is a pretty straight forward, it has dependency on the HttpRequestMessage as well as IHttpRoute and returns the version number. Also lets take care of some of the "Magic String" problem by creating a constant class as show below.

OwinConstants.cs

public static class OwinConstants
{
    public const string GET = "GET";
    public const string POST = "POST";
    public const string PUT = "PUT";

    public const char EqualsDelimiter = '=';
    public const char Period = '.';
    public const char Underscore = '_';
    public const char Semicolon = ';';
    

    public const string Version = "version";
    public const string VersionPrefix = "V";
    public const string RequestMethod = "owin.RequestMethod";
    public const string Controller = "controller";
    public const string ContentType = "Content-Type";
}

In that post I also mentioned that the version should be passed as an Accept header if it’s a GET and Content-Type header if it is a POST or PUT. However, when it comes to DELETE you don’t need a version as you are DELETING a resource and from a resource point of view it doesn’t make any sense to specify a version to be deleted. For example at a resource like /api/customer/1 it is very clear that you are looking for customer resource with an id 1 and for delete you just want to delete that id irrespective of what version you are supporting for that Web API.

So our logic will do a simple check from the OWIN pipeline to identity what the request type is and based on the type we extract the relevant header either from the Accept header or from the Content-Type header.

Another important thing to consider is that what do we do if there are no headers supplied? Depending on your requirements and discussion you may implement it differently. However, in my implementation I will use the one which is defined in the route table as a fall back value.

Lets put this all together in the code to see how it looks.

DefaultVersionSelector.cs

public class DefaultVersionSelector : IVersionSelector
{
    private const string versionFormat = "version={0}";
    public string GetVersion(HttpRequestMessage request, IHttpRoute route)
    {
        object routeVersion = string.Empty;
        string headerVersion = string.Empty;

        var owinEnvironment = request.GetOwinEnvironment();

        if (request.Method.Method == OwinConstants.POST || 
            request.Method.Method == OwinConstants.PUT)
        {
            headerVersion = GetVersionFromContentType(request);

            if (!string.IsNullOrEmpty(headerVersion))
            {
                return headerVersion;
            }
        }

        if (request.Method.Method == OwinConstants.GET)
        {
            headerVersion = GetVersionFromAcceptHeaderVersion(request);

            if (!string.IsNullOrEmpty(headerVersion))
            {
                return headerVersion;
            }
        }

        route.Defaults.TryGetValue(OwinConstants.Version, out routeVersion);
        return routeVersion as string;
    }

    private string GetVersionFromContentType(HttpRequestMessage request)
    {
        var versionList = new List<string>();
        var version = string.Empty;

        if (request.Content.Headers.ContentType == null)
        {
            throw new HttpResponseException(request.CreateResponse(HttpStatusCode.NotAcceptable));
        }

        request.Content.Headers.ToList().ForEach(x =>
        {
            if (x.Key.Contains(OwinConstants.ContentType))
            {
                foreach (var item in x.Value.ToList())
                {
                    if (item.Contains(OwinConstants.Version))
                    {
                        version = item.Split(OwinConstants.EqualsDelimiter)[1];
                    }
                }
            }
        });


        return version;
    }

    private string GetVersionFromAcceptHeaderVersion(HttpRequestMessage request)
    {
        string version = string.Empty;

        request.Headers.Accept.ToList().ForEach(headerValue =>
        {
             headerValue.Parameters.ToList().ForEach(v  =>
             { version = v.Value; });
        });

        return version;
    }
}

Pretty straight forward and now we will hook the above version selector into the ASP.NET Web API pipeline by simply inheriting from the DefaultHttpControllerSelector and overriding the quot&;SelectController" method, it’s that simple.

DefaultVersionControllerSelector.cs

public class DefaultVersionControllerSelector : DefaultHttpControllerSelector
{
    private const string versionFormat = "version={0}";

    private HttpConfiguration config;
    private IVersionSelector versionSelector;
    public DefaultVersionControllerSelector(HttpConfiguration config, 
                                            IVersionSelector versionSourceFactory) 
                                            : base(config)
    {
        this.config = config;
        this.versionSelector = versionSourceFactory;
    }

    public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
    {
        var controllers = GetControllerMapping();
        var routeData = request.GetRouteData();

        var controllerName = routeData.Values[OwinConstants.Controller].ToString();
        var owinEnvironment = request.GetOwinEnvironment();

        var version = versionSelector.GetVersion(request, routeData.Route);

        version = version.Replace(OwinConstants.Period, OwinConstants.Underscore);

        HttpControllerDescriptor controllerDescriptor;

        owinEnvironment.Add(OwinConstants.Version, new string[] { string.Format(versionFormat,version) });
        request.SetOwinEnvironment(owinEnvironment);

        var versionedControllerName = string.Concat(controllerName,
                                                    OwinConstants.VersionPrefix,
                                                    version);

        HttpControllerDescriptor versionedControllerDescriptor;

        if (controllers.TryGetValue(versionedControllerName, out versionedControllerDescriptor))
        {
            return versionedControllerDescriptor;
        }

        if (!string.IsNullOrEmpty(version) && versionedControllerDescriptor == null)
        {
            throw new HttpResponseException(
                          request.CreateResponse(HttpStatusCode.NotAcceptable));
        }

        var defaultControllerName = routeData.Route.Defaults[OwinConstants.Controller].ToString();

        controllers.TryGetValue(defaultControllerName, out controllerDescriptor);

        return controllerDescriptor;
    }
}

As you can see from the above code, first we extract controller name from the route data and then extract the OWIN environment variable from the HTTPRequestMessage object. We also took care of minor version of API by checking for a period delimiter in the version.

If we happen to find one then we replace the period delimiter with an underscore, as this will allow us to map the version to a valid C# controller class. For example if the version is specified as "version=1.1" for a controller name "values" then the output controller name will be "Values1_1Controller".

After this we try to get the list of all the controllers using the base class and check if we can create a controller using the route value, controller name and the version. If we succeed we return the controller descriptor as is otherwise we fall back to the default supported version of the controller which we are going to specify in routing configuration. I know the above explanation can be bit confusing and hard to understand but don’t worry it will all come together once I show you the routing configuration.

Lets create two controller and I’ll just use the run-of-the-mill "ValuesController" for simple illustration and the name of the two versioned controllers are going to be Values1Controller for version 1 and Values1_1Controller for version 1.1 as shown below.

ValuesV1Controller.cs

public class ValuesV1Controller : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "value1-Version1", "value2-version1" };
    }
}

ValuesV1_1Controller.cs

public class ValuesV1_1Controller : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "value1-Version1.1", "value2-version1.1" };
    }
}

And this is where the routing magic happens in our OWIN startup class.

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new {   id = RouteParameter.Optional, 
                    version= "1" });

        config.Services.Replace(typeof(IHttpControllerSelector), 
                                       new DefaultVersionControllerSelector(config, 
                                           new DefaultVersionSelector()));

        app.UseWebApi(config);
    }
}

Now I am going to use POSTMAN to request two GETS one for version 1 and for version 1.1 as shown below.

VERSION 1
Web API Versioning

VERSION 1.1
Versioning test in POSTMAN

And as you can see from the returned data that the version selector is working correctly and we are hitting the right controller.

OWIN and Web Api

November 30, 2014 Leave a comment

In this post I am going to talk about how to get started with WEB API project with OWIN . As usual I am going to start with File > New Project > ASP.NET Web Application > Empty Solution and run the following Powershell command to get all the necessary OWIN packages from nuget.

PM> Install-Package Microsoft.AspNet.WebApi.Owin
PM> Install-Package Microsoft.Owin.Host.SystemWeb
PM> Install-Package Microsoft.Owin.Diagnostics

As you may have noticed the second package is to run OWIN Middleware on IIS but you could easily change that to "OWIN Self host" and spawn the web api on a console application with no dependencies on IIS.

The primary motivation and goals of OWIN specification is to develop web application which are independent of Web Server technology like IIS. Another goal is to move away from the System.Web.dll as it’s a 13-year-old assembly. That time it served it’s purpose as it was designed mainly keeping ASP.NET Web Forms in mind but now has a lot of dead weight when it executes code. We still can’t get away with it but in the ASP.Net vNext it is gone and your web application will run faster and will scale better.

For more information on OWIN please visit the http://owin.org/ website.

Anyways back to OWIN, now we are going to write a start-up class which the OWIN runtime will use it to bootstrap our web application and this is how the start-up code looks like.

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseWelcomePage();
    }
}

This is how the OWIN pipeline identifies the startup routine with the above method signature. As you can see it takes an interface IAppBuilder in which you can plug your own middleware and in the above code we are plugging the welcome page middleware component to display the page. This is the pattern which is used in development where you will develop your own middleware and plug that into the app builder.

Now when we run the application we can see the OWIN "Welcome page "running using IIS Express.

Owin Startup Page

In the next step I am going to add a simple Customer Controller as shown below.

CustomerController.cs

public class CustomerController : ApiController
{
    private List<Customer> customers;

    public CustomerController()
    {
        customers = new List<Customer>();
        for (var i = 0; i < 3; i++)
        {
            customers.Add(new Customer
            {
                Id = i,
                FirstName = "First" + i,
                LastName = "Last" + i
            });
        }
    }

    // GET: api/Customer
    public IEnumerable<Customer> Get()
    {
        return customers;
    }

    // GET: api/Customer/5
    public Customer Get(int id)
    {
        return customers.FirstOrDefault(c => c.Id == i);
    }

    // POST: api/Customer
    public void Post(Customer customer)
    {

    }

    // PUT: api/Customer/5
    public void Put(int id)
    {

    }

    // DELETE: api/Customer/5
    public void Delete(int id)
    {
    }
}

So the controller code is done and let’s wire up the controller into the OWIN pipeline by adding the HttpConfiguration to the OWIN start-up class which has the routing configuration.

Here is the complete start-up class code.

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional });

        app.UseWebApi(config);
        app.UseWelcomePage();
    }
}

Lets do some quick tests in order to see if everything is working correctly. I am going to use the POSTMAN extension for Chrome and will execute following GET request.

/api/customer
/api/cutomer/1

and with no surprises here is the result of 2 request.

Customer Web Api with Get

Customer Web Api with Get specific customer

As you can see it is fairly simple to set up OWIN and start using it in a Web api application. Moreover, there are 2 more ways to define the OWIN start-up class. First either you can decorate your with assemblu attribute as shown below

assembly: OwinStartup(typeof(OwinTestingDemo.Startup))]

or you can define it in your web.config as

<appSettings>  
  <add key="owin:appStartup" value="OwinTestingDemo.Startup" />
</appSettings>

The choice of different startup may come handy in case for different environment you may want to run different middleware components.

That’s it for now and in the next post I am going to show how we can simplify testing web api with OWIN.