Search code examples
c#asp.net-web-apiowinself-host-webapi

OWIN SelfHost project running WebApi project does not call Application_Start method


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.


Solution

  • 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);
        ...
     }