仅用于GET请求的MVC自定义路由 [英] MVC Custom Routing only for GET requests
问题描述
我有一个自定义路由类,已将其添加到RouteConfig
I have a custom routing class which I added to the 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类如下:
The CustomRouting class looks like this:
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/*
路径的请求.
Essentially I want to process requests that go to the /custom/*
path with my custom rules.
但是:不应使用我的自定义规则来处理不是"GET"的请求.相反,我想删除路径开头的/custom
段,然后让MVC继续执行RouteConfig中配置的其余路由.
But: Requests that are not "GET", should not be processed with my custom rules. Instead, I want to remove the /custom
segment at the beginning of the path and then let MVC continue with the rest of the routing configured in RouteConfig.
我该如何实现?
推荐答案
您可以首先在HttpModule中过滤带有自定义"前缀的请求
You can start by filtering "custom" prefixed requests in an HttpModule
示例:
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()
{
}
}
然后,您可以为自定义"网址设置路由
Then you can have your routes for "custom" urls
routes.MapRoute(
name: "Default",
url: "custom/{action}/{id}",
defaults: new { controller = "Custom", action = "Index", id = UrlParameter.Optional }
);
注意:不要忘记在您的web.config中注册HttpModule
Note: Don't forget to register your HttpModule in your web.config
<system.webServer>
<modules>
<add type="MvcApplication.Modules.CustomRouteHttpModule" name="CustomRouteModule" />
</modules>
</system.webServer>
这篇关于仅用于GET请求的MVC自定义路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!