Web API Self-Hosting Using OWIN

One of my previous articles explained Self-hosting Web API Using Windows Application. Continuing on the same path, this article exlains how to self-host the Web API, using OWIN custom host. So let's start with it.

Add a new Console application and let's call it WebAPIOWINHosting.

Console application

Next, in order to create a Web API and use OWIN custom host, we add references to Microsoft.AspNet.WebApi.OwinSelfHost, using the Nuget Package Manager. This will not only add the references for the Web API but also the OWIN components, along with the other required dependencies.

webapi

Add a new Web API controller class. We remove all the methods and add a simple GET method to get the sum of two random numbers.

controller class

Add a new class named Startup.cs. This is as per the OWIN specifications. Use the HttpConfiguration class to create the Web API routing template and add it to the request pipeline using the appBuilder.UseWebApi method, where appBuilder is of type IAppBuilder.

appBuilder

Open the Program.cs file and start the server using the WebApp.Start method, specifying the StartUp class as the entry point for the settings required. This is the OWIN specification of starting the server in the custom host.

Program

Now simply run the application and the server is started.

run the application

To test the Web API, we will use the Chrome browser Postman extension. So enter the URL of the Web API that we specified in the Program.cs and Send the request. See the results received.

test the webapi

Easy to host, isn't it? If you learned it then do share it. The Source code of the example is also attached here. Happy coding!


Similar Articles