Inside Web API there is a hidden gem that isn't having the right interest, the Self-Host. The most typical mistake is to consider Web API as part of ASP.NET MVC. Really it doesn't and there aren't shared libraries between them.
In fact you can use Web API without ASP.NET MVC simply installing it from NuGet. The first advantage to be separated from MVC is the Self-Host.
What does it mean Self-Host in Web API?
The answer is really simple; you can “start” the application without use IISor IIS Express and, for this scenario, there are two important aspects:
- You can host your services in a simple console application, so double click on a “.exe” and you can start immediately use the Web API (IIS is a Windows service and is always started);
- You can create easily an integration test hosting the Web API inside your test suite;
Like previous, the answer is really simple. We need to create a console application and a few lines of code. The first step is to create new project from Visual Studio, choose Console Application and then install the Web API package:
Now, as for the web application, we have to create a folder for our controllers and put inside the classic ValuesController
:
publicclassValuesController:ApiController{publicIEnumerable<string>Get(){returnnew[]{"http://tostring.it","http://imperugo.tostring.it","http://twitter.com/imperugo","http://www.linkedin.com/in/imperugo"};}}
Right now we have to create only the host for the server, so:
usingSystem;usingSystem.Web.Http;usingSystem.Web.Http.SelfHost;namespaceimperugo.webapi.selfhost{internalclassProgram{privatestaticvoidMain(string[]args){varconfig=newHttpSelfHostConfiguration("http://localhost:12345");config.Routes.MapHttpRoute("Default","{controller}",new{controller="Home"});// Create servervarserver=newHttpSelfHostServer(config);// Start the serverserver.OpenAsync().Wait();Console.WriteLine("WebServerStarted");Console.WriteLine("Pressentertoexit");Console.ReadLine();}}}
Absolutely easy and fun.
You can download this sample cloning my spike repository from github http://s.tostring.it/Q1wt6U