zoukankan      html  css  js  c++  java
  • mvc中路由的映射和实现IHttpHandler挂载

    首先我们了解一下一般的方法

        我们只需要在web.config配置文件中做映射处理即可。

    第一种形式:

     <system.web>
        <urlMappings enabled="true">
    
          <add url="~/d" mappedUrl="SmackBio.WebSocketSDK.GenericHandler"/>
    
        </urlMappings>

    注释:这里的url就是我们需要在请求的具体写法,然后mappedUrl则是我们实际项目中的处理位置。

    第二种形式:

     <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>    
          <add path="/socket" verb="*" name="GenericHandler" type="SmackBio.WebSocketSDK.GenericHandler"/>
        </handlers>
      </system.webServer>
    

    注释:这里的path就是我们请求的入口地址,type则是我们的实际项目中的方法类位置。

    mvc路由配置方法

    这是我们不同使用的映射形式。但是在mvc路由中我们挂起一般处理程序却发现行不通了,下面我们就要配置路由方法进行映射。

    在mvc中我们分为三步:

        1.实现处理代码程序(实现一般处理程序继承类IHttpHandler)

     1   public class GenericHandler : IHttpHandler
     2     {
     3         public void ProcessRequest(HttpContext context)
     4         {
     5             if (context.IsWebSocketRequest || context.IsWebSocketRequestUpgrading)
     6             {
     7                 context.AcceptWebSocketRequest(new SBWebSocketHandler());
     8             }
     9             else
    10             {
    11                 context.Response.ContentType = "text/plain";
    12                 context.Response.Write("Service running");
    13             }
    14         }
    15 
    16         public bool IsReusable
    17         {
    18             get
    19             {
    20                 return false;
    21             }
    22         }
    23     }
    View Code

        2.定义一个类路由规则(实现路由IRouteHandler接口然后指向处理代码程序类)

     public class PlainRouteHandler : IRouteHandler
        {
    
            public IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                return new GenericHandler();
            }
        }
    
     public static void RegisterHandler(RouteCollection routes)
            {
               
                RouteTable.Routes.Add("socket",
                     new Route("socket", new MvcZodiac.Controllers.PlainRouteHandler()));
            }
    View Code

        3.注册到程序中(在Global.asax中的Application_Start方法注册)

     RegisterHandler(RouteTable.Routes);

     这里补充一下,这句话一定要写在路由注册之前,不然不会起作用。例如:

  • 相关阅读:
    The Future of Middleware and the BizTalk Roadmap
    FW: How to spawn a process that runs under the context of the impersonated user in Microsoft ASP.NET pages
    Strips illegal Xml characters
    luogu P2280 激光炸弹(二维前缀和)
    luogu P2704 炮兵阵地(经典状态压缩DP)
    SP1716 GSS3 Can you answer these queries III (线段树维护最大连续子段和)
    二分图判定、匹配问题
    C++语法综合 | 基于char*设计一个字符串类MyString
    luogu P1044 火车进出栈问题(Catalan数)
    C++设计模式 | 三种设计模式基础
  • 原文地址:https://www.cnblogs.com/yanbigfeg/p/8795136.html
Copyright © 2011-2022 走看看