我需要根据特定条件重写URL。我尝试在routeconfig.cs中添加条件检查,并为URL重写不同的routes.MapRoutes()方法,但这并不起作用。访问网站时,它会显示目录,从而导致错误。
以下是一个例子:
routes.MapRoute(...)
ClassA classA = new Class();
if(classA.IsThisTrue()) {
routes.MapRoute(...)
routes.MapRoute(...)
}
routes.MapRoute(...)
如果删除条件,则可以。
还有其他方法吗?
答案 0 :(得分:2)
您可以使用自定义约束:
public class MyCons : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
ClassA classA = new Class();
return classA.IsThisTrue();
}
}
然后在您的路线中使用它:
routes.MapRoute(
name: "myRoute",
// your own route
url: "myUrl/{myParam}",
defaults: new { controller = "Some", action = "Index" }
constraints: new { myParam= new MyCons() }
);
// other route
routes.MapRoute(
name: "myOtherRoute",
// your own route
url: "myOtherUrl/{myParam}",
defaults: new { controller = "Foo", action = "Index" }
constraints: new { myParam= new MyCons() }
);