I am trying to convert an existing ASP.NET Web API project (currently hosted in IIS) into one that can use the SelfHost framework. I'm a bit fuzzy on the actual details but understand I can run a self-host server in a console window and then run the service on top of it. The problem I'm having is that my project is an MVC project and not a console one. My familiarity with console/Windows apps is somewhat limited as I generally work with projects to be hosted in IIS.
What I'm a bit confused on is whether I need to convert my existing Web API project in Visual Studio into a new console application, or if there's a way to create another console application Project in the solution which can act as the web server for the Web API services, or rather if there's a way to add a console element with a Main() entry point to the existing MVC project (overriding the Global.asax entry point.)
Search didn't yield much information that helps me fill this knowledge gap. Hoping someone can point me in the right direction. Even at a high level.
I recently had to convert a Web API project into a self-hosted service using OWIN (on Visual Studio 2013). I did that as follows:
(1) Manually added Program.cs and Startup.cs files at the root of the project. Both files containing code as described here: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api.
(2) Went to the properties of the Web API project. On the "Applications" section, I stated "Output Type" as "Console Application", and set the "Program" class as the "Startup object".
Although not required, I slightly modified the "using" block within Program.Main() to look as follows:
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
if (response != null)
{
Console.WriteLine("Information from service: {0}", response.Content.ReadAsStringAsync().Result);
}
else
{
Console.WriteLine("ERROR: Impossible to connect to service");
}
Console.WriteLine();
Console.WriteLine("Press ENTER to stop the server and close app...");
Console.ReadLine();
}
Finally, instead of calling config.Routes.MapHttpRoute() multiple times within Startup.Configuration(), you can refer to the routes you already wrote for the Web API:
// Configure Web API for self-host.
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);