c# – What is the right way to self-host a Web API?-ThrowExceptions

Exception or error:

I’m not asking for a best practice advice since there are numerous blog posts and tutorials about the topic all over the internet.

I’m asking out of confusion since Microsoft made a lot of change to the whole self hosting procedure and every tutorial I find take a different, deprecated or unfamiliar approach.

My goal is to set up a self hosted Web API in a legacy Windows Service to control various long running tasks from a non-Windows client, such as an Android application where integrating a WCF / SOAP client can really be a PITA.

I’m aware about the fact that WCF is capable of offering a RESTful service, but since Web API is really suited for such a task, I thought I gave it a shot.

This is how I currently start my API hosted using OWIN (Katana):

public class ApiBootstrap {

    var httpConfiguration = new HttpConfiguration();
    // ... configure routes etc.

    appBuilder.UseWebApi(httpConfiguration);     // appBuilder = IAppBuilder
    var disposable = WebApp.Start<ApiBootstrapper>(_myBaseUri);

}

But most tutorials go on a different approach:

var config = new HttpSelfHostConfiguration("http://localhost:999");
// ... configure routes etc..

var server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();

Now, I understand the HttpSelfHostServer class is from System.Web.Http.SelfHost and not using OWIN, and both work fine.

But I’m struggling for days to achieve very simple tasks such as securing the connection using SSL, creating authorization etc., just because every tutorial I find on those topics referr to the self hosted method not using OWIN. But AFAIK, OWIN (Katana) is Microsofts prefered approach to achieve self hosting.

As a beginner, I am completely confused and helpless!

Edit: 4 upvotes, 1 fav and 30 views in only 6 minutes but still no answer. Can’t really say if I’m doing genious coffee stuff here or if it’s just an incredible dumb question.

How to solve:

The HttpSelfHostServer is now marked as legacy on Nuget. However, the Owin HTTPListener has only been RTM for a fairly short period of time now.

Also, part of the intent of Owin to ensure that how you setup middleware is identical regardless of how you host. So you will not likely see many articles targeting Owin HttpListener hosting directly because it should be irrelevant which host you are using.

The OwinHttpListener currently uses the standard .net HttpListener under the covers, which in reality is the same thing that the HttpSelfHostServer used. Therefore stuff like SSL should be configured in pretty much the same way.

As far as authentication is concerned, have you looked at Microsoft.Owin.Security, most likely everything you need is in there.

Leave a Reply

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