Use Session in WebAPI, and use Session in WebAPI
Recently, when modifying a WebApp, you need to change the Captcha written in the previous generic processing routine to a WebApi-based implementation mechanism. during the implementation process, it is found that the IRequiresSessionState session cannot be used either (context. session = null)
I checked some articles and found that the RouteHandler needs to be rewritten before the api routing can be used. The following example uses ASP.net MVC 4 to describe how to implement HttpControllerHandler and HttpControllerRouteHandler and overwrite them.
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); } }
In WebApiConfig, change config. Routes. MapHttpRoute
RouteTable. Routes. MapHttpRoute (using System. Web. Routing) and specify RouteHandler
public static void Register(HttpConfiguration config){ RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ).RouteHandler=new SessionControllerRouteHandler();}
Or by default, Session support is not enabled in MVC WebApi. You must
GlobalOverride the Init method to specify the type 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); }
Or:
public override void Init() { this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required); base.Init(); }
It is disabled by default. SessionStateBehavior has four values:
Default uses the Default ASP. NET logic to determine the request session Status and behavior. The default logic is to find whether the API for marking the session status exists in IHttpHandler.
Disabled does not enable session status to process requests. This setting overwrites any session behavior that has been determined by the request handler.
ReadOnly enables read-only sessions for requests. This means that the session status cannot be updated. This setting overwrites any session Status behaviors that have been determined by the request handler.
Required enables full read/write session status for the request. This setting overwrites any session behavior that has been determined by the request handler.