zoukankan      html  css  js  c++  java
  • Asp.Net Web API中使用Session,Cache和Application的几个方法

        在ASP.NET中,Web Api的控制器类派生于ApiController,该类与ASP.NET的Control类没有直接关系,因此不能像在Web MVC中直接使用HttpContext,Cache,Session等,要使用的话,一般是从System.Web.HttpContext.Current静态对象引用HttpContext,从而使用Session等状态数据。

        不过,要在控制器类中通过HttpContext的Session属性直接使用Session状态数据,将抛出nullreference异常,网查主要有两种解决方案,一个是重载Global的init()方法,在该方法中开放Session状态,另一个设计带Session的路由处理器

        重载Global的Init()

    public class WebApiApplication : System.Web.HttpApplication
    {
            public override void Init()
            {
                this.PostAuthorizeRequest += (y, z) => HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
                base.Init();
            }
            protected void Application_Start()
            {
                GlobalConfiguration.Configure(WebApiConfig.Register);
            }
    }

    设计路由处理器

      建立HttpControllerHandler和HttpControllerRouteHandler并覆写

     public class SessionStateRouteHandler : IRouteHandler
      {
            public IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                return new SessionableControllerHandler(requestContext.RouteData);
            }
     }
     public class SessionableControllerHandler:HttpControllerHandler,IRequiresSessionState
     {
            public SessionableControllerHandler(RouteData routeData)
                :base(routeData)
            {
    
            }
     }

       创建RouteConfig类型并配置路由

     public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection route)
            {
                route.MapHttpRoute(
                  name: "WebApiRoute1",
                  routeTemplate: "api/{controller}/{id}",
                  defaults: new { id = RouteParameter.Optional }
                ).RouteHandler = new SessionStateRouteHandler();
            }
        }

     在Global中注册配置

    protected void Application_Start()
    {
                // GlobalConfiguration.Configure(WebApiConfig.Register);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
  • 相关阅读:
    12月19号 init和class
    12月18号 property关键字
    12月18号 属性property
    12月17号 类和对象
    12月17号 OC语言准备
    12月16号 文件操作
    12月16号 双链表
    12月15号 单链表
    2015.12.07 ATM
    2015.12.03 命名规范 输入输出 运算符 条件语句 循环语句
  • 原文地址:https://www.cnblogs.com/yan7/p/7800122.html
Copyright © 2011-2022 走看看