2015-09-18 105 views
-1

我正在使用MVC 5.1和AutoFac。MVC路由衝突似乎很奇怪

我不明白爲什麼從這個URL每個控制器衝突以下路線:https://localhost:44300/Home/login

我認爲這將映射到第一個方法。我得到這個錯誤:

發現多個控制器類型與URL匹配。如果多個控制器上的屬性路由匹配請求的URL,就會發生這種情況

請求發現下列匹配控制器類型: AllThings.WebUI.Controllers.AccountController AllThings.WebUI.Controllers.PostController


public class AccountController : Controller 
{ 
    // 
    // GET: /Account/Login 
    [Route("~/{site}/Login")] 
    [Route("~/Account/Login")] 
    [Route("~/{country:maxlength(2)}/{site}/Login")] 
    [Route("~/{country:maxlength(2)}/Account/Login")] 
    [AllowAnonymous] 
    public ActionResult Login(string returnUrl, string country, string site) 
    { 
     return View(); 
    } 
} 


    public class PostController : Controller 
{ 
    [Route("~/{site}/{CategoryUrl?}")] 
    [Route("~/{country:maxlength(2)}/{site}/{CategoryUrl?}", Name = "ResultList")] 
    [AllowAnonymous] 
    public ActionResult List(string country, string site, SearchCriteriaViewModel searchCriteriaViewModel) 
    { 
     return View("List", searchCriteriaViewModel); 
    } 
} 

回答

1

的主要問題是,你必須3個可能的路由可以匹配/Home/Login

[Route("~/{site}/Login")] 
[Route("~/Account/Login")] 
[Route("~/{site}/{CategoryUrl?}")] 

自由使用佔位符,特別是那些你在URL模板定義中所擁有的東西並不是件好事。您應該在網址中使用文字,或者如果您使用佔位符,則應對它們設置約束,以免發生衝突。

注意以下擊潰衝突,以及:

[Route("~/{country:maxlength(2)}/{site}/Login")] 
[Route("~/{country:maxlength(2)}/Account/Login")] 
[Route("~/{country:maxlength(2)}/{site}/{CategoryUrl?}", Name = "ResultList")] 

它們中的任何一個可以匹配UK/Account/Login

此外,使用代字號(~)將覆蓋路由前綴(請參閱MSDN documentation)。如果你的控制器沒有定義一個,你應該從第一個段或佔位符開始。