Alternative to use HttpContext in System.Web for Owin Alternative to use HttpContext in System.Web for Owin asp.net asp.net

Alternative to use HttpContext in System.Web for Owin


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


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.


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.Identityto get to the identity. All three will get you the same identity object.

and yes, OwinContext is available this way too.