2015-09-25 55 views
0

我需要根據特定條件重新編寫URL。我嘗試在routeconfig.cs中添加條件檢查並附上不同的路由。URL的URLRoutes()方法重寫但不起作用。訪問網站時,它顯示目錄,這會導致錯誤。如何在routeconfig.cs中創建條件

下面是一個例子:

routes.MapRoute(...) 

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

routes.MapRoute(...) 

如果我刪除的條件,它的工作原理。

有沒有其他方法可以做到這一點?

+4

你能告訴你的代碼?它沒有你的條件工作嗎? –

+1

您如何期待這項工作?路線是在應用程序啓動時建立的,並且是「常量」。他們不瞭解一旦建立的條件邏輯。 –

+0

1.我們不知道你的「病情」是什麼。 2.我們並沒有真正做到你做了什麼。 – DPac

回答

1

您可以使用自定義的約束本:

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