在自托管OWIN的Web

在自托管OWIN的Web

本文介绍了在自托管OWIN的Web API,如何在关机时运行code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我自托管使用这些code片段一OWIN的Web API:

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")

我想,当我的Web API服务关闭运行一些code。我正在寻找类似 HttpApplication.Application_End ,一个处置事件或一个精心布置的覆盖无效的Dispose()

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().

我如何运行code当Web API服务关闭?

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

推荐答案

这可以通过获取主机的取消标记并用它注册一个回调像这样取得

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

有人告诉我,有人在武士刀队,这关键是主机特定的功能,因此可能无法在所有主机上存在。 Microsoft.Owin.Host.SystemWeb不实现这一点,但我不知道其他人。

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.

最简单的方式来验证这是否会为你工作是检查 app.Properties host.OnAppDisposing 键。

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

这篇关于在自托管OWIN的Web API,如何在关机时运行code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 14:24