Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access HttpContext.Current.Session from Web API

Is it possible to access HttpContext.Current.Session through a WebAPI ? can we make it inheriting IRequiresSession?

I have a generic handler doing a Session set after an API call which I want to remove.

public void AccountController : ApiController, IRequiresSessionState { public void Login() { setsession(){} }  } 
like image 897
Kubi Avatar asked Nov 09 '13 23:11

Kubi


People also ask

How do I access HttpContext in Web API?

ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.

Is it possible to use session in Web API?

But in practice, yes - you may need to access a user's session from a web API. By default this is not possible.

How do I find HttpContext current?

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically: public Task Invoke(HttpContext context) { // Do something with the current HTTP context... }

What is System Web HttpContext current session?

HttpContext. Current. Session simply returns null if there is no session available. The HttpApplication's implementation of the Session property throws an HttpException with the message Session state is not available in this context.


1 Answers

Technically, yes, although I'd really advise against this practice - a REST API should be completely stateless (cookies and other client-side state is OK).

If you absolutely must do this, you can grab the HTTP context like so:

var context = Request.Properties["MS_HttpContext"] as HttpContext; 

At which point you just use its Session property to get the session.

Note that this breaks certain contracts assumed by System.Net.Http - specifically it means your API controllers can never be self-hosted because they're coupled to ASP.NET. If you're OK with this, and with the fact that your API controllers may not work properly from a web farm unless you re-architect everything to use distributed sessions - well then, go for it.

P.S. It is also possible to use IRequiresSessionState, but you can't use it on the controller itself, you need to use it on an HttpControllerHandler and set it as the RouteHandler. The approach is discussed in this MSDN thread. Again, I can't recommend strongly enough against this idea, it violates the basic principle of a Web API - but, if you've got a really good reason for it, then it's another option which is a bit more reusable.

like image 163
Aaronaught Avatar answered Sep 18 '22 15:09

Aaronaught