WebApi Application_Start will not fire until web p

2019-08-26 17:08发布

问题:

I have WebApi OWIN hosted Web Server/Winforms Client application.

Additionally I am using SignalR for client/server communication.

When running under IIS Express while debugging Application_Start method in Global.asax.cs is executing just fine.

On IIS 7.5 same code in Global.asax.cs will not execute when website is started in IIS Manager

Application_Start only fires when I call it from a page http://localhost:7000/SignalR/hubs or Client sends SignalR request first time around and after that server code is running correctly.

I could add code to "warm" up my server by sending a request first time client ever sends a request but I want to avoid it.

回答1:

When running under IIS Express while debugging Application_Start method in Global.asax.cs is executing just fine.

That is because lauching your app with VS will automatically open browse which execute first request. So the server receive its first request indirectly by your action through VS.

Application_Start only fires when I call it from a page http://localhost:7000/SignalR/hubs or Client sends SignalR request first time around and after that server code is running correctly.

This is the default configuration. Application_Start event get executed when first request is received. But you can change that through configuration in web.config. So you must use <applicationInitialization> element as explained by Microsoft:

The <applicationInitialization> element specifies that web application initialization is performed proactively before a request is received. An application can start up more quickly if initialization sequences such as initializing connections, priming in-memory caches, running queries, and compiling page code are performed before the HTTP request is received.

By the way to do it without warming up your server, you need to move to a higher version of IIS. Minimum version required is IIS 8. The documentation link added above explains how to active this functionnality.

If you think your initialization process can be time consuming (cache initialization etc...), this configuration element also allows you to configure a static page or splashscreen that will be displayed to use until the initialization finished. For that you use remapManagedRequestsTo attribute on <applicationInitialization>.

So finally your configuration should look like this in your web.config:

<system.webServer>
   <applicationInitialization
      doAppInitAfterRestart="true"
      skipManagedModules="true"
      remapManagedRequestsTo="path_to_your_static_file_to _show">
   </applicationInitialization>
</system.webServer>

For more information don't forget to click on the documentation link I added early.