不使用HttpContext获取当前的OwinContext

15

随着

HttpContext.Current.GetOwinContext()

我可以在Web应用程序中接收当前的OwinContext。

使用OwinContext.Set<T>OwinContext.Get<T>,我存储应该在整个请求期间存在的值。

现在我有一个组件,应该在Web和控制台owin应用程序中使用。 在此组件中,我目前无法访问HTTP上下文。

在我的应用程序中,我正在使用线程和异步功能。

我还尝试使用CallContext,但在某些情况下似乎会丢失数据。

如何访问当前的OwinContext?或者是否有其他上下文可以使用来存储我的值?

1个回答

7
我使用WebApi AuthorizationFilter来执行以下操作,如果你有中间件支持,也可以在MVC控制器和WebApi控制器上下文中执行此操作,例如对于WebApi,app.UseWebApi(app)。组件必须支持Owin管道,否则不确定如何获取正确线程的上下文。因此,您可以创建自己的自定义OwinMiddleware,并在Owin启动时使用app.Use()将其连接到此组件。更多信息here。我的属性中间件。
public class PropertiesMiddleware : OwinMiddleware
{
    Dictionary<string, object> _properties = null;

    public PropertiesMiddleware(OwinMiddleware next, Dictionary<string, object> properties)
        : base(next)
    {
        _properties = properties;
    }

    public async override Task Invoke(IOwinContext context)
    {
        if (_properties != null)
        {
            foreach (var prop in _properties)
                if (context.Get<object>(prop.Key) == null)
                {
                    context.Set<object>(prop.Key, prop.Value);
                }
        }

        await Next.Invoke(context);
    }
}

Owin启动配置

public void Configuration(IAppBuilder app)
{

        var properties = new Dictionary<string, object>();
        properties.Add("AppName", AppName);

        //pass any properties through the Owin context Environment
        app.Use(typeof(PropertiesMiddleware), new object[] { properties });
}

WebApi 过滤器

public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext context, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{

        var owinContext = context.Request.GetOwinContext();
        var owinEnvVars = owinContext.Environment;
        var appName = owinEnvVars["AppName"];
}

愉快的编程!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接