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

Wallace Kelly picture Wallace Kelly · Apr 27, 2014 · Viewed 12.7k times · Source

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?

Answer

arthas picture arthas · Sep 23, 2014

I think there is a better way to get the CancellationToken:

var properties = new AppProperties(app.Properties);
CancellationToken token = properties.OnAppDisposing;

AppProperties is under namespace Microsoft.Owin.BuilderProperties, which comes from this nuget package: http://www.nuget.org/packages/Microsoft.Owin/

The description of property OnAppDisposing says:

Gets or sets the cancellation token for “host.OnAppDisposing”.

Please refer to: http://msdn.microsoft.com/en-us/library/microsoft.owin.builderproperties.appproperties%28v=vs.113%29.aspx