Alternative to use HttpContext in System.Web for Owin

此生再无相见时 提交于 2019-11-27 22:03:21

问题


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.

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

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

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.


回答1:


You can use OwinRequestScopeContext. Which is doing exactly what you are looking for.




回答2:


This article gives me the solution:

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

by

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

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




回答3:


After reading this. It seems to me that extending AuthorizeAttribute is still the way to go. However, since HttpContext is IIS based, we want to avoid using it from now on.

There is a HttpActionContext got passed in. Then we could use

actionContext.Request.GetRequestContext().Principal.Identity

or

actionContext.RequestContext.Principal.Identity

OR

actionContext.Request.GetOwinContext().Request.User.Identity to get to the identity. All three will get you the same identity object.

and yes, OwinContext is available this way too.



来源:https://stackoverflow.com/questions/24572794/alternative-to-use-httpcontext-in-system-web-for-owin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!