1. Establish Httpcontrollerhandler and Httpcontrollerroutehandler in Webapiconfig and overwrite it
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 to be modified to the following format:
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. In MVC Webapi, the session support is not enabled by default. You need to override the Init method in global to specify the types that the session needs to support
public override void Init () { postauthenticaterequest + = mvcapplication_postauthenticaterequest; Base. Init (); } void Mvcapplication_postauthenticaterequest (object sender, EventArgs e) { HttpContext.Current.SetSessionStateBehavior (sessionstatebehavior.required); }
MVC4 WEBAPI Development If you want to support the session, please do the following several aspects of the problem