Skip to main content

Use OWIN to Self-Host ASP.NET Web API

In this article we are going to learn about how to self-host Asp.Net Web API using OWIN.
For defination, you can refer OWIN - Katana.

As we know katana component architecture divided application into 4 components
  1. Host
  2. Server
  3. Middleware
  4. Application 

So by referring above image you can easily understand we need to implement 4 components and the same numbers of steps to host web api using OWIN.

STEP 1 (HOST COMPONENT)
- Create an console application and run the below command in Package Manager Console



 install-package Microsoft.Owin.Hosting



It will add the following reference in console project.

 After completing the first step you can update your console app like below.
namespace LearnOnlineAsp.Net
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://localhost:8080";

            using (Microsoft.Owin.Hosting.WebApp.Start<Startup>(url))
            {
                System.Console.ReadKey();
            }
        }
    }

    public class Startup
    {
        public void Configuration(Owin.IAppBuilder app)
        {

        }
    }
}

But when you run the console you will get runtime exception.
System.MissingMemberException: 'The server factory could not be located for the given input: Microsoft.Owin.Host.HttpListener'
Means now the time to implement step 2

STEP 2 (SERVER COMPONENT)
For adding server components run the below command in Package Manager Console



 It will add the Microsoft.Owin.Host.HttpListner reference in the project.

means now it will not thrown any exception when you run the console app.


After completing step 2 now our console app can understand http request and response.

using Microsoft.Owin.Hosting;
using Owin;
using System;

namespace LearnOnlineAsp.Net
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://localhost:8080";

            using (WebApp.Start<Startup>(url))
            {
                Console.WriteLine("Owin WebApp Hosting started..");
                Console.WriteLine("Press any key for stop.");
                Console.ReadKey();
            }
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(ctx =>
            {
                return ctx.Response.WriteAsync("Hello world from web app");
            });
        }
    }
}

But our goal is to run Web Api then move to next step

STEP 3 (MIDDLEWARE COMPONENT)
To add the Web API in middleware components run the below command in Package Manager Console
PM> install-package Microsoft.Aspnet.WebApi.Owin

It will add the following reference in console project.







Add the app.UseWebApi as Middleware component, follow the below codes

using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Web.Http;

namespace LearnOnlineAsp.Net
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://localhost:8080";

            using (WebApp.Start<Startup>(url))
            {
                Console.WriteLine("Owin WebApp Hosting started..");
                Console.WriteLine("Press any key for stop.");
                Console.ReadKey();
            }
        }
    }

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

        private void WebApiMiddleware(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new { controller = "example", id = RouteParameter.Optional });

            app.UseWebApi(config);
        }
    }
}

Now the time is create api application

Step 4 (APPLICATION)
Add the api controller class in console application













final source code

using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Web.Http;

namespace LearnOnlineAsp.Net
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://localhost:8080";

            using (WebApp.Start<Startup>(url))
            {
                Console.WriteLine("Owin WebApp Hosting started..");
                Console.WriteLine("Press any key for stop.");
                Console.ReadKey();
            }
        }
    }

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

        private void WebApiMiddleware(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new { controller = "example", id = RouteParameter.Optional });

            app.UseWebApi(config);
        }
    }

    public class ExampleController: ApiController
    {
        public IHttpActionResult Get()
        {
            return Ok("Hello world from Web API");
        }
    }
}

Here steps I am repeating again

Step 1
install-package Microsoft.Owin.Hosting

Step 2
install-package Microsoft.Owin.Host.HttpListener

Step 3
install-package Microsoft.Aspnet.WebApi.Owin

Step 4
Create Web api class

Please comment below about the article.