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

后端 未结 2 1130
执笔经年
执笔经年 2020-12-01 10:53

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 afte

相关标签:
2条回答
  • 2020-12-01 11:08

    Casting it as HttpContext did not work for me using Web Api 2.1. However I could use HttpContextWrapper.

    var context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;
    
    0 讨论(0)
  • 2020-12-01 11:20

    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.

    0 讨论(0)
提交回复
热议问题