first class, SessionRouteHandler, inherits from HttpControllerHandler, and implements the IRequiresSessionState interface. In fact, IRequiresSessionState has no internal methods, so there is no need to write anything.
public class SessionRouteHandler : HttpControllerHandler,IRequiresSessionState { public SessionRouteHandler(RouteData routeData) : base(routeData) { } }
The second class, SessionControllerRouteHandler, inherits from HttpControllerRouteHandler
public class SessionControllerRouteHandler : HttpControllerRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { return new SessionRouteHandler(requestContext.RouteData); } }
After completing these two classes, you can move on to the next step.
Step 2: Modify WebApiConfig, give a hint to the novice, this class can be seen in Global, WebApiConfig.Register(... is in progress here. In general, in the App_Start directory. Since we want to make WebApi can obtain the Session set in the Controller in MVC, so this configuration needs to be changed.
//config.Routes.MapHttpRoute( // name: "DefaultApi", // routeTemplate: "api/{controller}/{id}", // defaults: new { id = RouteParameter.Optional } //); //Pass Session on Route RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter.Optional}).RouteHandler = new SessionControllerRouteHandler();
Well, after all is completed, it can be compiled. At this time, you can create a Session in the Controller in the normal way, for example:
Session["ValidCode"]="Session Test"
Then you can get it in WebApi:
HttpContext.Current. Session["ValidCode"].ToString() is
transferred from: https://www.cnblogs.com/ca47/p/4603701.html