问题
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 }
);
}
}
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;
}
}
Essentially I want to process requests that go to the /custom/*
path with my custom rules.
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.
How can I achieve that?
回答1:
You can start by filtering "custom" prefixed requests in an HttpModule
HTTP Handlers and HTTP Modules Overview
Example :
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 }
);
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>
来源:https://stackoverflow.com/questions/42249948/mvc-custom-routing-only-for-get-requests