1

I have a solution in Visual Studio 2019 containing two projects:

  1. A C# class library (a WebAPI project)
  2. A C# console application (An OWIN SelfHost project, referring to project 1)

The sole purpose of the SelfHost project is that the WebAPI can be run without Visual Studio.

When I run the WebAPI project in Visual Studio, everything works fine. Static content is served and I can invoke its ApiControllers via the browser.

When I run the SelfHost project, the ApiControllers cannot be invoked/reached by the browser. This is likely because the following code in Global.asax does not get executed. The Application_Start method is not invoked:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

Hence, the mechanism to link controllers to URIs is not executed:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

So the symptom can be explained, but how to fix? I tried to fix this by invoking the GlobalConfiguration.Configure method manually from the SelfHost project, but then I got the following error:

'This method cannot be called during the application's pre-start initialization phase.'

Any help is appreciated.

  • 1
    You'll need to migrate from "the old way" of using Application_Start method and put your initialisation code in Startup.cs. – Chris Pickford Jul 18 '19 at 12:21
  • 1
    Yep, @Chris is right. If you'd like to go with Owin's self-hosted approach, please see [this](https://stackoverflow.com/a/52693106/8327106) – Angel Dinev Jul 18 '19 at 12:27
  • You are confusing some things here. You are actually creating IIS hosted project, not self-hosted. You certainly see the IIS Express running. The `global.asax` is not handled at all by Katana. Start here: https://dotnetcodr.com/2014/04/14/owin-and-katana-part-1-the-basics/ – ZorgoZ Jul 18 '19 at 12:28
  • @ZorgoZ there are two projects, one is self-hosted (if you run this it starts IIS in the systray) and one is not (which starts a command-line application i.o IIS). – Wouter van Koppen Jul 18 '19 at 13:51

1 Answers1

1

I solved it by migrating my original code to the WebAPI 2 way (as suggested by Chris Pickford). It's now written as follows and it works:

Startup.cs:

public void Configuration(IAppBuilder app)
{
    ...
    var config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();
    app.UseWebApi(config);
    ...
 }