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

时间:2017-02-15 12:51:57

标签: c# asp.net-mvc asp.net-mvc-routing

我有一个自定义路由类,我已添加到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类看起来像这样:

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 个答案:

答案 0 :(得分: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()
    {
    }
}

然后你可以获得“自定义”网址的路线

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>