同
HttpContext.Current.GetOwinContext()
Run Code Online (Sandbox Code Playgroud)
我可以在Web应用程序中收到当前的OwinContext.
使用OwinContext.Set<T>和OwinContext.Get<T>我存储应该为整个请求提供的值.
现在我有一个应该在web和console owin应用程序中使用的组件.在此组件中,我目前无法访问http上下文.
在应用程序中我使用线程和异步功能.
我也试过使用CallContext但是这似乎在某些场景中丢失了数据.
那我怎么能访问当前的OwinContext?还是有其他背景我可以发挥我的价值观?
我使用WebApi AuthorizationFilter执行以下操作,如果您有中间件支持它,例如app.UseWebApi(app)用于WebApi,您还应该能够在MVC控制器和WebApi控制器上下文中执行此操作.
该组件必须支持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);
}
}
Run Code Online (Sandbox Code Playgroud)
Owin StartUp配置
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 });
}
Run Code Online (Sandbox Code Playgroud)
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"];
}
Run Code Online (Sandbox Code Playgroud)
快乐的编码!
| 归档时间: |
|
| 查看次数: |
18796 次 |
| 最近记录: |