Self hosting Web API controller

September 04, 2013 by Anuraj

.Net .Net 4.0 Web API Windows Forms

This post is about self hosting your Web API controller. Similar to WCF, Web API can be hosted either on IIS or in Windows Process, can be a windows application or console application or a windows service. Self hosting can be used for unit testing purposes also, instead of mocking can use the in memory server. In this post I am hosting the web api in a console application.

For implementing the self hosting, first you need to add reference of the following assemblies.

  • System.Net.Http
  • System.Web.Http
  • System.Web.Http.SelfHost
  • Newtonsoft.Json

Then you need to configure the routing, similar to the WebApiConfig.cs. After configuring the routes, you can create instance of the SelfHost server by passing the instance of the configuration.

Here is the implementation.

static void Main(string[] args)
{
    var baseUrl = "http://localhost:8081";
    var config =
        new HttpSelfHostConfiguration(baseUrl);
    config.Routes.MapHttpRoute(
        "Default", "api/{controller}/{id}",
        new { id = RouteParameter.Optional });

    using (var server = new HttpSelfHostServer(config))
    {
        server.OpenAsync().Wait();
        Console.WriteLine("Server started, listening on {0}", baseUrl);
        Console.WriteLine("Press <ENTER> to exit.");
        Console.ReadLine();
        server.CloseAsync().Wait();
    }
}

You have created self hosting server. Now you can add the Web API controller. Create a class, which inherits from ApiController class. Here is my hello world controller, which return a string.

public class HelloWorldController : ApiController
{
    public string Get()
    {
        return "Hello World";
    }
}

You are successfully hosted the Web API controller in a console application. Now open the browser and point to http://localhost:8000/api/HelloWorld, which will return a JSON string.

Web API Self Hosting

You may get some Access denied exception, if you are not running your Visual Studio or the console application in Administrator mode.

Happy Programming.

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub