Posted by Anuraj on Wednesday, September 4, 2013 Reading time :1 minute
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.
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.
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.
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.
You may get some Access denied exception, if you are not running your Visual Studio or the console application in Administrator mode.
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.