我使用WebApi AuthorizationFilter執行以下操作,如果您有中間件來支持它,例如app.UseWebApi(app)for WebApi,您也應該可以在MVC控制器和WebApi控制器上下文中執行此操作。
該組件必須支持Owin管道,否則不知道如何從正確的線程獲取上下文。
因此,也許你可以創建自己的自定義
OwinMiddleware
在你Owin啓動wireup使用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"];
}
快樂編碼!