仅适用于 GET 请求的 MVC 自定义路由

MVC Custom Routing only for GET requests

我有一个自定义路由 class,我将其添加到 RouteConfig

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 class 如下所示:

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 中配置的其余路由。

我怎样才能做到这一点?

您可以从在 HttpModule

中过滤 "custom" 前缀请求开始

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()
    {
    }
}

然后你可以为 "custom" urls

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

注意:不要忘记在 web.config

中注册 HttpModule
<system.webServer>
  <modules>
    <add type="MvcApplication.Modules.CustomRouteHttpModule" name="CustomRouteModule" />
  </modules>
</system.webServer>