Recently in the rewriting of WebApp to the previous use of the generic processing routines written captcha to use WEBAPI to implement the mechanism, in the process of implementation found that the use of IRequiresSessionState session is also unavailable (context. Session==null)
I have checked some articles before we find that we need to rewrite the Routehandler in order to use it in registering API routes. The following is a description of the part to be implemented using ASP. 4来 to build Httpcontrollerhandler and Httpcontrollerroutehandler 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); } }
Change Config.Routes.MapHttpRoute into a webapiconfig
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, in the MVC Webapi, the session support is not enabled by default. Need to be
GlobalOverride the Init method 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); }
Or:
public override void Init () {this . Postauthenticaterequest + = (sender, E) = HttpContext.Current.SetSessionStateBehavior ( sessionstatebehavior.required); Base. Init (); }
It is not turned on by default. The Sessionstatebehavior has four values:
default ASP is used. NET logic to determine the session state behavior of the request. The default logic is to look for the presence of a tagged session state interface in IHttpHandler.
Disabled Session state is not enabled to process requests. This setting overrides any session behavior that has been determined by the handler that inspected the request.
ReadOnly enables read-only session state for requests. This means that the session state cannot be updated. This setting overrides any session state behavior that has been determined by the handler that inspected the request.
The Required enables full read-write session state behavior for the request. This setting overrides any session behavior that has been determined by the handler that inspected the request.
Using session in ASP. Webapi