- A+
Web APi全局启动Session
以下皆在Global.asax全局文件中进行。
首先开启Session功能(重写Init方法)
- /// <summary>
- /// 开启WebAPI中的Session支持
- /// </summary>
- public override void Init()
- {
- this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
- base.Init();
- }
第一步(定义两个变量)
- private const string WebApiPrefix = "api";
- private static string WebApiExecutePath = string.Format("~/{0}", WebApiPrefix);
第二步(获取当前请求的路径)
- private bool isWebAPiRequest()
- {
- return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiExecutePath);
- }
第三步(若请求Web APi则启动Session)
- protected void Application_PostAuthorizeRequest()
- {
- if (isWebAPiRequest())
- {
- HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
- }
- }
第四步(测试代码)
- HttpContext.Current.Session.Add("UserId", "1");
- var UserId = HttpContext.Current.Session["UserId"];