2017-02-15 48 views
0

我有我加入RouteConfigMVC自定义路由仅适用于GET请求

public static class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.Add(new CustomRouting()); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 

的CustomRouting类看起来像这样的自定义路由类:

public class CustomRouting : RouteBase 
{ 
    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var requestUrl = httpContext.Request?.Url; 
     if (requestUrl != null && requestUrl.LocalPath.StartsWith("/custom")) 
     { 
      if (httpContext.Request?.HttpMethod != "GET") 
      { 
       // CustomRouting should handle GET requests only 
       return null; 
      } 

      // Custom rules 
      // ... 
     } 
     return null; 
    } 
} 

基本上我想进程请求使用我的自定义规则转到/custom/*路径。

但是:请求不是“GET”,不应该使用我的自定义规则处理。相反,我想在路径起始处删除/custom,然后让MVC继续执行RouteConfig中配置的其余路由。

我该如何做到这一点?

回答

1

您可以通过在一个HttpModule过滤 “定制” 为前缀的请求启动

HTTP Handlers and HTTP Modules Overview

例子:

public class CustomRouteHttpModule : IHttpModule 
{ 
    private const string customPrefix = "/custom"; 

    public void Init(HttpApplication context) 
    { 
     context.BeginRequest += BeginRequest; 
    } 

    private void BeginRequest(object sender, EventArgs e) 
    { 
     HttpContext context = ((HttpApplication)sender).Context; 
     if (context.Request.RawUrl.ToLower().StartsWith(customPrefix) 
     && string.Compare(context.Request.HttpMethod, "GET", true) == 0) 
     { 
      var urlWithoutCustom = context.Request.RawUrl.Substring(customPrefix.Length); 
      context.RewritePath(urlWithoutCustom); 
     } 
    } 

    public void Dispose() 
    { 
    } 
} 

然后你可以有你的 “定制” 的URL路径

routes.MapRoute(
     name: "Default", 
     url: "custom/{action}/{id}", 
     defaults: new { controller = "Custom", action = "Index", id = UrlParameter.Optional } 
    ); 

注意:不要忘记注册你的HttpModule在你的web.config

<system.webServer> 
    <modules> 
    <add type="MvcApplication.Modules.CustomRouteHttpModule" name="CustomRouteModule" /> 
    </modules> 
</system.webServer> 
+0

好主意。谢谢! – Sandro