WebAPI启用session功能

第一步:简单建立两个类,以备修改WebApi的路由方式

第一个类SessionRouteHandler,继承自HttpControllerHandler,并同时实现一下IRequiresSessionState接口,其实IRequiresSessionState是没有内部方法的,因此也不需要写啥。
 public class SessionRouteHandler : HttpControllerHandler,IRequiresSessionState
 {
         public SessionRouteHandler(RouteData routeData) : base(routeData)
         {
         }
 }


第二个类SessionControllerRouteHandler,继承自HttpControllerRouteHandler
 public class SessionControllerRouteHandler : HttpControllerRouteHandler
 {
         protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
         {
             return new SessionRouteHandler(requestContext.RouteData);
         }
 }


完成这两个类之后,就可以进行下一步了。

第二步:修改WebApiConfig,给新手提示一下,这个类在Global中可以看到,WebApiConfig.Register(......这里在进行的。一般情况下,在App_Start目录下。由于我们是要让WebApi能获得MVC中Controller中设置的Session,故要重改一下这个配置。

//config.Routes.MapHttpRoute(
             //    name: "DefaultApi",
             //    routeTemplate: "api/{controller}/{id}",
             //    defaults: new { id = RouteParameter.Optional }
             //);

             //Route上传递Session
             RouteTable.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new {id = RouteParameter.Optional}).RouteHandler = new SessionControllerRouteHandler();


好了,全部完成后可以编译了,这时候,你可以在Controller中按照正常方式建立Session了,例如:

Session["ValidCode"]="Session Test"
那么WebApi中就可以获取到了:

HttpContext.Current.Session["ValidCode"].ToString()


转自:https://www.cnblogs.com/ca47/p/4603701.html

猜你喜欢

转载自yh-fly.iteye.com/blog/2399905
今日推荐