Timo Korinth

2 Meter, 2 Mark

Build a WebAPI Self-hosting server

| 0 comments

If you don’t want to host your WebAPI services in an IIS Webserver, you can create your own small webserver and run it without installation of any 3rd party applications.

To demonstrate this, you should create a new Console Application first:

NewConsoleApplicationSelfHostServer

On the next step you have to install a set of additional assemblies. To simplify this task, you can search for the NuGet package “Microsoft WebAPI Self Host” on the NuGet Package Manager and install it:

NuGetPackageWebAPISelfHost1NuGetPackageWebAPISelfHost2

All you have to do now is to write a few lines of code and start your console application to get a fully functional webserver for your WebAPI services up and running:

class Program
{
    static readonly Uri _baseAddress = new Uri("http://localhost:60064/");

    static void Main(string[] args)
    {
        // Set up server configuration
        HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // Create server
        var server = new HttpSelfHostServer(config);

        // Start listening
        server.OpenAsync().Wait();
        Console.WriteLine("Web API Self hosted on " + _baseAddress + " Hit ENTER to exit...");
        Console.ReadLine();
        server.CloseAsync().Wait();
    }
}

ATTENTION: Be sure to start your Visual Studio (or the .exe application) as Administrator. Otherwise it can’t register the appropriate services for you and your webserver will not work!

Leave a Reply