I have a solution in Visual Studio 2019 containing two projects:
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.
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);
...
}