Self Hosting WebAPI with Katana

Wednesday, July 24, 2013

A few weeks ago we looked at a minimalistic Katana based project to serve a static response from a console application. For more fun we can throw in the WebAPI with only a little more work. The first step is adding a package that forms a bridge between the OWIN/Katana host and the WebAPI.

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost -IncludePreRelease

The OwinSelfHost package depends on some of the core WebAPI packages, so one install command will bring in everything we need to get WebAPI up and running.

WebAPI does require some configuration to process requests, and we need to provide a routing rule describing how to map incoming requests to controllers. The configuration is always done using an instance of an HttpConfiguration object. In a traditional ASP.NET hosting scenario we access an existing WebAPI configuration object through GlobalConfiguration.Configuration, but in a self hosting scenario we need to create our own. Let’s create a custom class.

public class MyHttpConfiguration : HttpConfiguration
{
    public MyHttpConfiguration()
    {
        ConfigureRoutes();
        ConfigureJsonSerialization();
    }

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

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

Back in the Startup class, we no longer need to configure our own async handler to say “Hello, World!”. Instead we’ll add the WebAPI with the UseWebApi extension method provided by WebApi.OwinSelfHost, and an instance of our custom config class.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new MyHttpConfiguration();
        app.UseWebApi(config); 
    }
}

The UseWebApi method installs a piece of Katana middleware (topic for a future post) that adapts HTTP request and response messages in the OWIN pipeline to and from the HttpRequestMessage and HttpResponseMessage objects that form the core of the WebAPI abstraction, as well as configuring the environment for the message processing. For example, setting Thread.CurrentPrincipal.

Now all need is a model and a controller.

public class Greeting
{
    public string Text { get; set; }
}

public class MessageController : ApiController
{
    public Greeting Get()
    {
        return new Greeting
        {
            Text = "Hello, World!"
        };
    }
}

Finally, we can run the application and verify that IE11 still uses Notepad to display JSON payloads.

json with ie11


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!