How to Self-Host a Web API with .NET Framework
Sometimes you just want to host an HTTP endpoint from your existing code. You may have an existing process, but you need some sort of HTTP way to interact with the running process. The advantage of hosting within an existing process isn’t obvious, but it allows us to deploy an HTTP endpoint without having to add another process to our list of “deployables”. Another reason I have used this technique is that it allows us to expose a little bit of information about how a process is running.
Making a running process return an HTTP endpoint is simple in the .NET world. With .NET Core it is basically the default. With .NET Framework, it requires a little more work. .NET Framework assumes you are running web applications inside of a .NET Framework web application project. But, as mentioned before, sometimes you just want to host a website inside of your existing process.
In this blog post, we are not only going to look at how to host a web application inside of our .NET Framework process, but also hosting an Angular application within that application.
Step 1 – Add Some NuGet References
Take your existing application and adding a NuGet reference for Microsoft.AspNet.WebApi.SelfHost. This library will be used to host the HTTP endpoint within our application.
Step 2 – Fire Up Your Self-Hosted Server
This is pretty basic when using the code Microsoft has provided. You just need to provide a little bit of configuration, then create a class of type HttpSelfHostServer and you are good to go. In the code below, you will notice some routes being configured. The best part of this configuration is that anyone that has configured ASP.NET MVC routes will be right at home writing these configurations.
Step 3 – Writing the Web Controllers
For this simple demo, we will write two controllers. One that handles the returning the Angular web application and another controller to be our fake search API.
Step 4 – Writing the API Controller
Writing the API controller for search is straightforward and pretty much normal Web API code, it’s just hosted differently. In this demo, we are just returning a generic result but this could be wired up to return real search results.
Closing and Additional Resources
The need to host an ASP.NET web application from within a .NET Framework project isn’t something that comes up every day. For nearly all applications, I recommend following a more standard hosting path. If you’re on the ground, I typically recommend IIS, while if you’re hosting in the cloud I recommend something like an Azure App Service or an Azure Function.
There are still times when the ability to host an HTTP endpoint from within your existing service or application can be useful. I rarely make this my go-to option, but it is nice to know that doing it with .NET Framework is pretty straightforward.
Refer to this Microsoft writeup for more information on self-hosting an ASP.NET web API.