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);

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

  • 相关阅读:
    .ssh/config 常用配置
    openresty(nginx) 配置 http与https使用同一个端口,禁止 IP 直接访问
    uni-app 入门小白纯徒手编写组件 hello-popup
    CSS 是啥?前端小白入门级理解
    爱思助手备份 iPhone 时没有设置密码,恢复备份时需要密码的问题
    introduction-to-64-bit-assembly
    flv to mp4
    Hopper Disassembler系列之Sublime Text 3 爆破
    Hopper 学习
    微信小游戏 Three.js UI 2D text 简单方案
  • 原文地址:https://www.cnblogs.com/yanbigfeg/p/8795136.html
Copyright © 2011-2022 走看看