是否有可能对来自Web API来访问HttpContext.Current.Session [英] Is it possible to access HttpContext.Current.Session from Web API

查看:111
本文介绍了是否有可能对来自Web API来访问HttpContext.Current.Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能访问HttpContext.Current.Session通过的WebAPI?我们可以把它继承IRequiresSession?

我有一个通用的处理程序做了会议,我想删除一个API调用后设置。

 公共无效的AccountController:ApiController,IRequiresSessionState
{
公共无效登录()
{
setsession(){}
}
}


解决方案

技术上的,是的,但我真的建议反对这种做法 - 一个REST API应该是完全无状态(cookies和其他客户端-side状态OK)。

如果你绝对的必须的做到这一点,你可以抓住的HTTP上下文,像这样:

  VAR背景= Request.Properties [MS_HttpContext]作为HttpContext的;

此时你只需要使用它的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.httpcontext.session%28v=vs.110%29.aspx\">Session属性来获取会话。

请注意,这打破了由 System.Net.Http 假设某些合同 - 具体而言,它意味着你的API控制器绝不可能自承载因为他们连接到ASP。净。如果你确定这一点,并与事实,你的API控制器可能无法正确​​地从一个Web场,除非你重新设计的一切使用分布式会议的工作 - 那么,去了

P.S。也可以使用 IRequiresSessionState ,但你不能使用它的控制器本身,你需要使用它在一个 HttpControllerHandler 键,将其设置为 RouteHandler 。这种方法是在这个MSDN线程讨论。同样,我不能推荐足够强烈的针对这个想法,它违反了一个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(){}
} 
}

解决方案

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.

这篇关于是否有可能对来自Web API来访问HttpContext.Current.Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆