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

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

 

posted @ 2018-04-11 13:18  YanBigFeg  阅读(395)  评论(0编辑  收藏  举报