2

我想創建一個路由約束,但不知道什麼是最好的。這裏是沒有限制的路線:ASP.NET MVC 3路由約束:正則表達式爲非空

context.MapRoute(
    "Accommodation_accomm_tags", 
    "accomm/{controller}/{action}/{tag}", 
    new { action = "Tags", controller = "AccommProperty" }, 
    new { tag = @"" } //Here I would like to put a RegEx for not null match 
); 

什麼是最好的解決方案呢?

回答

6

爲什麼你需要一個不爲空/空匹配的約束?一般來說,如果你像這樣定義您的路線:

context.MapRoute(
    "Accommodation_accomm_tags", 
    "accomm/{controller}/{action}/{tag}", 
    new { action = "Tags", controller = "AccommProperty" }, 
); 

tag未在請求URL這條路根本不會匹配指定。

如果你想有一個令牌是可選的,則:

context.MapRoute(
    "Accommodation_accomm_tags", 
    "accomm/{controller}/{action}/{tag}", 
    new { action = "Tags", controller = "AccommProperty", tag = UrlParameter.Optional }, 
); 

約束用於當你想給定路由標記的值限制在一些特定的格式。

+0

這是一個很好的觀點。 – Cymen

+0

你又釘了一遍。我試圖記住,應該有一個簡單的方法,但我不能。現在很清楚。謝謝! – tugberk

+0

如果你的動作等待字符串參數呢?在這種情況下,如果您將標籤指定爲可選參數,它將包含空值。 – Vokinneberg

8

你能創建一個IRouteConstraint

public class NotNullRouteConstraint : IRouteConstraint 
{ 
    public bool Match(
    HttpContextBase httpContext, Route route, string parameterName, 
    RouteValueDictionary values, RouteDirection routeDirection) 
    { 
    return (values[parameterName] != null); 
    } 
} 

,你可以線了:

context.MapRoute(
    "Accommodation_accomm_tags", 
    "accomm/{controller}/{action}/{tag}", 
    new { action = "Tags", controller = "AccommProperty" }, 
    new { tag = new NotNullRouteConstraint() } 
); 
+0

我也這麼認爲,如果我找不到RegEx爲非null,這將是解決方案。謝謝 ! – tugberk

2

起初,我試圖創建一個空字符串的正則表達式是^$(這是空將會)。但是,它看起來不像路線約束可能是!=。如何將一個或多個字符與^.+$匹配?

所以:

tag = @"^.+$" 
+0

你有兩個句子是完全相反的:'我相信你想要一個空字符串的正則表達式......'和'...你當然不是空字符串......' – tugberk

+0

那麼他要求RegExp對於實際上爲空字符串的null,但他希望與路由約束相反。 – Cymen

+0

我明確指出,我需要RegEx爲非空字符串。你可以在我的代碼示例中看到它作爲註釋:'//在這裏,我想把一個正則表達式爲非空匹配'我沒有要求任何地方的空符合RegEx。對不起,但很感謝你的努力。 – tugberk