替代使用的HttpContext的System.Web中的Owin [英] Alternative to use HttpContext in System.Web for Owin

查看:376
本文介绍了替代使用的HttpContext的System.Web中的Owin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET身份验证现在基于可以在任何基于OWIN主机上使用OWIN中间件。 ASP.NET身份的不会对任何的System.Web依赖

ASP.NET authentication is now based on OWIN middleware that can be used on any OWIN-based host. ASP.NET Identity does not have any dependency on System.Web.

我有一个AuthorizeAttribute过滤器,我需要获得当前用户,并添加一些属性可以通过动作控制器后取回。

I have an AuthorizeAttribute filter where I need to get the current user and add some properties to be retrieved later by action controllers.

问题是,我必须使用的HttpContext至极所属的System.Web。是否有Owin HttpContext的任何选择吗?

The problem is that I have to use the HttpContext wich belongs to System.Web. Is there any alternative of HttpContext for Owin?

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);
    }
}

请注意:我发现<一个href=\"http://stackoverflow.com/questions/23814265/what-to-use-instead-of-httpcontext-when-using-owin-without-system-web\">this问题,似乎至极重复,但求为NancyFx项目工作的一个解决方案,至极它并不适用于我。

Note: I found this question, wich seems a duplicate, but asks for a solution working for NancyFx project, wich it's not valid for me.

推荐答案

<一个href=\"http://brockallen.com/2013/10/27/host-authentication-and-web-api-with-owin-and-active-vs-passive-authentication-middleware/\"相对=nofollow>这篇文章给我的解决方案:

网页API 2引入了新的
  RequestContext的类,它包含一个主属性。这是现在
  适当的位置,以查找呼叫者的身份。这个
  替换Thread.CurrentPrincipal中和/或在现有的机制
  HttpContext.User中。这也是你会分配给你是什么
  写code认证中的Web API调用者。

Web API 2 introduced a new RequestContext class that contains a Principal property. This is now the proper location to look for the identity of the caller. This replaces the prior mechanisms of Thread.CurrentPrincipal and/or HttpContext.User. This is also what you would assign to if you are writing code to authenticate the caller in Web API.

因此​​,只要修改了这一行:

So just modifying the line:

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

Guid userId = new Guid(actionContext.RequestContext.Principal.Identity.GetUserId());

现在,已经不再需要到的System.Web参考。

now, the reference to System.Web is not needed anymore.

这篇关于替代使用的HttpContext的System.Web中的Owin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆