Search code examples
c#asp.net-web-apiowin

In self-hosted OWIN Web API, how to run code at shutdown?


I am self-hosting a OWIN Web API using these code snippets:

class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();
        var route = config.Routes.MapHttpRoute("DefaultApi", "{controller}");
        appBuilder.UseWebApi(config);
    }
}

WebApp.Start<Startup>("http://localhost:8080")

I would like to run some code when my Web API service shuts down. I'm looking for something like HttpApplication.Application_End, a Disposed event, or a well-placed override void Dispose().

How do I run code when the Web API service shuts down?


Solution

  • This can be achieved by getting the host's cancelation token and registering a callback with it like so

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var context = new OwinContext(app.Properties);
            var token = context.Get<CancellationToken>("host.OnAppDisposing");
            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    // code to run
                });
            }
        }
    }
    

    I was told by someone on the Katana team that this key is for host specific functionality and therefore may not exist on all hosts. Microsoft.Owin.Host.SystemWeb does implement this, but I'm not sure about the others.

    The easiest way to verify if this will work for you is to check app.Properties for the host.OnAppDisposing key.