通过继承RouteBase,这种事情很容易做到。它允许您使用几乎任何您想要分析请求的逻辑,并根据请求中的内容将其定向到特定的操作方法。
这是一条使用http://localhost/Default.aspx?action=Index2 和http://localhost/Default.aspx?action=Edit 示例的路线
public class CustomRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
// Trim off the leading "/"
var path = httpContext.Request.Path.Substring(1);
if (path.Equals("Default.aspx", StringComparison.OrdinalIgnoreCase))
{
result = new RouteData(this, new MvcRouteHandler());
result.Values["controller"] = "Home";
result.Values["action"] = httpContext.Request.QueryString["action"] ?? "Index";
}
// IMPORTANT: Returning null tells the routing framework to try
// the next registered route.
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
// Returning null skips this route.
// Alternatively, implement a scheme to turn the values passed here
// into a URL. This will be used by UrlHelper to build URLs in views.
return null;
}
}
可以像这样用MVC注册。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new CustomRoute());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "WebApplication23.Controllers" }
);
}
}
请注意,已注册的订单路线很重要。
如果您坚持使用filename.extension 模式,还有一件事 - 您必须配置 IIS 以允许请求到达 MVC,因为默认情况下为 any URL with a . in it will throw a 404 not found error。
<system.webServer>
<handlers>
<add name="ApiURIs-ISAPI-Integrated-4.0"
path="/Default.aspx"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>