1、在App_Start/WebApiConfig.cs中建立建立HttpControllerHandler和HttpControllerRouteHandler 并覆写它:
public class SessionRouteHandler : HttpControllerHandler,IRequiresSessionState { public SessionRouteHandler(RouteData routeData) : base(routeData) { } } public class SessionControllerRouteHandler : HttpControllerRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { return new SessionRouteHandler(requestContext.RouteData); } }
2.在App_Start/WebApiConfig.cs中config.Routes.MapHttpRoute要修改为下面的格式:
//config.Routes.MapHttpRoute( // name: "DefaultApi", // routeTemplate: "{controller}/{action}/{id}", // defaults: new { id = RouteParameter.Optional } //); //改成下面的 RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ).RouteHandler = new SessionControllerRouteHandler();
3.在MVC的WebApi中默认是没有开启Session会话支持的。需要在Global中重写Init方法来指定会话需要支持的类型
public override void Init() { PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest; base.Init(); } void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e) { HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required); }