Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to use HttpContext in System.Web for Owin

Tags:

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 which 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, which seems a duplicate, but asks for a solution working for NancyFx project, which is not valid for me.

like image 503
Xavier Egea Avatar asked Jul 04 '14 10:07

Xavier Egea


People also ask

When should I use HttpContext items?

Similarly, you use HTTPContext Items collection when you are sharing the same information across the different instance based on the user request and that request could be changed for a different request.

What is HttpContext in Web API?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.

What is HttpContext HTTP request and Httpresponse?

HttpRequest is a subset of HttpContext . In other words, the HttpContext includes the response, the request, and various other data that's not relevant to a specific request or response; such as the web application, cached data, server settings and variables, session state, the authenticated user, etc.

What is Owin used for in Web API?

Open Web Interface for . NET (OWIN) defines an abstraction between . NET web servers and web applications. OWIN decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.


1 Answers

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

like image 108
nsgocev Avatar answered Sep 28 '22 11:09

nsgocev