asp.net web api 開啟HttpContext 的Session功能
阿新 • • 發佈:2019-02-19
在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();
}
}