Xavier Egea Xavier Egea - 3 years ago 250
ASP.NET (C#) Question

Alternative to use HttpContext in System.Web for Owin

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)

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.

Answer Source

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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download