More on OWIN: Web API

In our previous edition, I’ve done a small app with OWIN. Although OWIN’s been around for quite a while (and probably due to be replaced by .net core?) there wasn’t a lot of incentive for developers to use it. Maybe, there are but given that most developers that work on C# will host it on IIS, it made a lot of sense to use the standard approach.

So today, I’m going to expand on what we covered with “how do we tie in Web API with OWIN?”

Handily, there’s an app middle-ware for that!

So let’s expand on our previous working example of OWIN and create an api controller.


    public class HelloController : ApiController
    {
        public object Get(string id)
        {
            return new {ID = string.Format("Hello {0}!", id)};
        }
    }

Next, let’s define a HttpConfiguration to deal with the routing things.

    public class WebApiConfig : HttpConfiguration
    {
        public WebApiConfig()
        {
            ConfigureRoutes();
            ConfigureSerializer();
        }

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

        private void ConfigureSerializer()
        {
            var jsonSettings = Formatters.JsonFormatter.SerializerSettings;
            jsonSettings.Formatting = Formatting.Indented;
            jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }

So here all pretty normal, but do we tie them all up? We add this code to the Startup.cs’ file.


app.UseWebApi(new WebApiConfig());    //added support for webapi

and it’s all done! Simples! source code here.

Playing around with OWIN

What exactly is OWIN?

OWIN stands for Open Web Interface for .Net. It’s a Microsoft specification to decouple the server from the web applications that is built on top of it.

Why should you care?

For one, it gives you the ability to host it anywhere, and standalone. It also allows you to test the application as a whole in isolation, without requiring installation into the IIS and running fully functional test.


Having said that, I’ve never actually dabbled in Nancy / OWIN / Katana so I took a short time today and wrote a classic hello world with it.

So let’s start with creating a project in visual studio. Here we’ll pick a web application, and let’s create an empty application.

new_web_app_for_owin

The first few things we have to do is to grab some nuget packages.

OWIN

These are packages are required for OWIN self hosting.

Next let’s create Startup class. I suspect this is the insertion point of OWIN.

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(context =>
            {
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync("{ \"message\" : \"hello world!\"}");
            });
        }
    }

The code basically start up a context and returns a JSON object with the message hello world.

Helpfully one of the nuget packages we’ve downloaded is “OwinHost”, which allows us to fire up the web application from command line.

owin_command_prompt

go to the root folder where the project is sitting (*hint* , same directory as the web.config) and type in the following


../packages/OwinHost.3.0.1/tools/OwinHost.exe

It goes back down a folder to normally where the packages will sit and goes back all the way up to OwinHost.exe.

owin_start

Here we can see that the web server has boot up to default port 5000. So let’s use postman and ask for a response using a standard get request.

postman_owin

profit!

We have a standalone running application without IIS!

Source code here.