asp.net web api 开启HttpContext 的Session功能
2014-04-12 12:59
405 查看
在Controller里:
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
var context = HttpContext.Current;
context.Session["a"] = "aaa";
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
var ses = HttpContext.Current.Session["a"];
return ses.ToString();
}
}
执行时出报异常,这时要在Global.asax里添加:开启Session功能
public class WebApiApplication : System.Web.HttpApplication
{
public override void Init()
{
this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
base.Init();
}
}
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
var context = HttpContext.Current;
context.Session["a"] = "aaa";
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
var ses = HttpContext.Current.Session["a"];
return ses.ToString();
}
}
执行时出报异常,这时要在Global.asax里添加:开启Session功能
public class WebApiApplication : System.Web.HttpApplication
{
public override void Init()
{
this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
base.Init();
}
}
相关文章推荐
- asp.net web api 开启HttpContext 的Session功能
- Generating a new ASP.NET session in the current HTTPContext
- asp.net中处理程序调用HttpContext.Current.Session获取值出错
- Asp.net中的HttpContext
- asp.net web api http put delete , iis 返回400.0 找不到错误的解决办法.
- ASP.NET 使用HttpContext.Current.Cache
- ASP.NET Web API(二):安全验证之使用HTTP基本认证
- Asp.Net HttpHandler 实现验证码功能
- (asp.net session总为null得到解决)了解IHttpModule接口事件执行顺便 获取Session 和SQL
- File Upload using jQuery AJAX in ASP.NET Web API or Http handler (AJAX上传文件通过Web API或 http handler)
- ASP.NET Web API的消息处理管道: HttpRoutingDispatcher
- ASP.NET状态管理之四(暂存状态HttpContext.Items)
- asp.net HttpHandler操作Session的函数代码
- ASP.NET状态管理之四(暂存状态HttpContext.Items)
- 模拟HttpContext 实现ASP.NET MVC 的单元测试
- windows8如何开启IIS功能支持asp、asp.net操作图解
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【五】——在Web Api中实现Http方法(Put,Post,Delete)
- asp.net mvc中在使用async的时候HttpContext为null的问题
- Asp.Net HttpApplication请求管道与Session(二)
- ASP.NET MVC4 WEB API入门 第二篇:ASP.NET MVC入门基础(2)—— 简单登录功能的实现