如何在routeconfig.cs中创建条件

本文关键字:创建 条件 cs routeconfig | 更新日期: 2023-09-27 18:14:36

我需要根据特定条件重写url。我试图在routeconfigs中添加条件检查,并将不同的路由。maproutes()方法用于URL重写,但这不起作用。当访问网站时,显示目录,导致错误。

下面是一个例子:

routes.MapRoute(...)
ClassA classA = new Class();
if(classA.IsThisTrue()) {
  routes.MapRoute(...)
  routes.MapRoute(...)
}
routes.MapRoute(...)

如果我删除条件,它就能工作。

有其他方法吗?

如何在routeconfig.cs中创建条件

您可以使用自定义约束:

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() }
);