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.

var config = new HttpSelfHostConfiguration("http://localhost:5150");

config.Routes.MapHttpRoute(
    "API Default", "api/{controller}/{id}", 
    new { id = RouteParameter.Optional });

config.Routes.MapHttpRoute(
    "Static", "{*url}",
    new { controller = "StaticFiles", action = "Index" });

using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{

    server.OpenAsync().Wait();
    // ... REST OF CODE
}

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.

public class StaticFilesController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Index(string url)
    {
        if (string.IsNullOrWhiteSpace(url))
            url = "index.html";

        var path = GeneratePath(url);
        var response = new HttpResponseMessage();
        response.Content = new StringContent(File.ReadAllText(path));
        response.Content.Headers.ContentType = ContentType(url);
        return response;
    }
}

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.

public class SearchController : ApiController
{
    [HttpGet]
    public SearchResult Search(string query)
    {
        return new SearchResult()
        {
            Query = query,
            Items = new SearchResultItem[]
            {
                new SearchResultItem()
                {
                    FilePath = "test",
                    Highlight = "Some sort of test..."
                }
            }
        };
    }
}

Conclusion

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. You can always deploy your .NET website on our hosting environment.

Refer to this Microsoft writeup for more information on self-hosting an ASP.NET web API.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *