2017-02-15 72 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