【问题标题】:MVC Custom Routing only for GET requestsMVC 自定义路由仅适用于 GET 请求
【发布时间】:2017-02-15 12:51:57
【问题描述】:

我有一个添加到 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 中配置的其余路由。

我怎样才能做到这一点?

【问题讨论】:

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


    【解决方案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>
    

    【讨论】:

    • 好主意。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2015-11-29
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多