在自托管的 OWIN Web API 中,如何在关机时运行代码? [英] In self-hosted OWIN Web API, how to run code at shutdown?

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

问题描述

我正在使用这些代码片段自托管 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 服务关闭时运行一些代码.我正在寻找类似 HttpApplication.Application_EndDisposed 事件或位置良好的 override void 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().

如何在 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
            });
        }
    }
}

Katana 团队的某个人告诉我,此密钥用于主机特定的功能,因此可能并非在所有主机上都存在.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.Propertieshost.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 中,如何在关机时运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆