Self-Host ASP.NET WebAPI 2 using OWIN

Setup

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

2. Create a new class Startup.cs to configure the WebAPI

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host.
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: “DefaultApi”,
            routeTemplate: “api/{controller}/{id}”,
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }
}

 

3. Add a Controller derived from ApiController valuescontroller.cs

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { “value1”, “value2” };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return “value”;
    }

    // POST api/values
    public void Post([FromBody]string value)
    {     }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {     }

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

 

4. Start the Owin Host (Console App or a Windows Service)

static void Main()
{
    string baseAddress = “
http://localhost:9000/”; 
    Microsoft.Owin.Hosting.WebApp.Start<Startup>(url: baseAddress);
    Console.ReadLine(); // Prevent Exit
}

5. Calling the WebAPI

Request

GET http://localhost:9000/api/values HTTP/1.1
Host: localhost:9000
Accept: application/json

Response

HTTP/1.1 200 OK
Content-Length: 19
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0

[“value1″,”value2”]

Reference: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api