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.
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.
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