繁体   English   中英

在不使用 HttpContext 的情况下获取当前的 OwinContext

[英]Getting Current OwinContext without using HttpContext

HttpContext.Current.GetOwinContext()

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

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

现在我有一个应该在 web 和控制台 owin 应用程序中使用的组件。 在这个组件中,我目前无权访问 http 上下文。

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

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

如何访问当前的 OwinContext? 或者是否有其他环境可以让我发挥我的价值观?

我使用 WebApi AuthorizationFilter 执行以下操作,如果您有中间件支持它,例如 app.UseWebApi(app) for WebApi,您也应该能够在 MVC 控制器和 WebApi 控制器上下文中执行此操作。

该组件必须支持 Owin 管道,否则不确定如何从正确的线程获取上下文。

所以也许你可以创建自己的自定义

Owin中间件

在 Owin 启动中使用 app.Use() 连接此组件。

更多信息在这里

我的属性中间件

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"];
}

快乐编码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM