替代在System.Web中为Owin使用HttpContext

Xav*_*gea 23 c# asp.net owin katana asp.net-identity

ASP.NET身份验证现在基于OWIN中间件,可以在任何基于OWIN的主机上使用.ASP.NET Identity 对System.Web没有任何依赖性.

我有一个AuthorizeAttribute过滤器,我需要获取当前用户并添加一些属性以供操作控制器稍后检索.

问题是我必须使用属于System.Web的HttpContext.对于Owin有没有HttpContext的替代方案?

public class WebApiAuthorizeAttribute : AuthorizeAttribute 
{
    public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        base.OnAuthorization(actionContext);

        Guid userId = new Guid(HttpContext.Current.User.Identity.GetUserId());

        ApplicationUserManager manager = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext())) { PasswordHasher = new CustomPasswordHasher() };
        ApplicationUser user = await manager.FindByIdAsync(userId);

        actionContext.Request.Properties.Add("userId", user.LegacyUserId);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我发现这个问题,似乎是重复的,但要求为NancyFx项目工作的解决方案,这对我来说无效.

nsg*_*cev 9

您可以使用OwinRequestScopeContext.这正是你正在寻找的.


Xav*_*gea 9

这篇文章给了我解决方案:

Web API 2引入了一个包含Principal属性的新RequestContext类.现在这是查找调用者身份的正确位置.这取代了Thread.CurrentPrincipal和/或HttpContext.User的先前机制.如果您要编写代码以在Web API中验证调用方,那么这也是您要分配的内容.

所以只需修改该行:

Guid userId = new Guid(HttpContext.Current.User.Identity.GetUserId());
Run Code Online (Sandbox Code Playgroud)

通过

Guid userId = new Guid(actionContext.RequestContext.Principal.Identity.GetUserId());
Run Code Online (Sandbox Code Playgroud)

现在,不再需要对System.Web的引用.