1、在WebApiConfig中建立建立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); } }
Routes.MapHttpRoute要修改为下面的格式:
public static void Register(HttpConfiguration config) { RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ).RouteHandler = new SessionControllerRouteHandler(); }
2、在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); }
学习交流群:364976091