您可以创建一个新的 Route,覆盖 GetVirtualPath
方法。在此方法中,将斜线添加到 VirtualPath
后面。像这样:
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
VirtualPathData path = base.GetVirtualPath(requestContext, values);
if (path != null)
path.VirtualPath = path.VirtualPath + "/";
return path;
}
为了简洁起见,我将整个示例发布在CodePaste.net上。
现在,您只需使用routes.MapRouteTrailingSlash()
而不是routes.MapRoute()
来注册路由即可。
routes.MapRouteTrailingSlash("register",
"register",
new {controller = "Users", action = "Register"}
);
当调用GetVirtualPath()
时,该路由将会向路径添加一个斜杠,这是RedirectToAction()
所做的。
更新:由于CodePaste链接失效,这里提供完整代码:
public class TrailingSlashRoute : Route {
public TrailingSlashRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler) {}
public TrailingSlashRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
: base(url, defaults, routeHandler) {}
public TrailingSlashRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,
IRouteHandler routeHandler)
: base(url, defaults, constraints, routeHandler) {}
public TrailingSlashRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,
RouteValueDictionary dataTokens, IRouteHandler routeHandler)
: base(url, defaults, constraints, dataTokens, routeHandler) {}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) {
VirtualPathData path = base.GetVirtualPath(requestContext, values);
if (path != null)
path.VirtualPath = path.VirtualPath + "/";
return path;
}
}
public static class RouteCollectionExtensions {
public static void MapRouteTrailingSlash(this RouteCollection routes, string name, string url, object defaults) {
routes.MapRouteTrailingSlash(name, url, defaults, null);
}
public static void MapRouteTrailingSlash(this RouteCollection routes, string name, string url, object defaults,
object constraints) {
if (routes == null)
throw new ArgumentNullException("routes");
if (url == null)
throw new ArgumentNullException("url");
var route = new TrailingSlashRoute(url, new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints)
};
if (String.IsNullOrEmpty(name))
routes.Add(route);
else
routes.Add(name, route);
}
}
services.Configure<RouteOptions>(routeOptions => { routeOptions.AppendTrailingSlash = true;};
,其中services
是一个IServiceCollection
。 - Ahmed