2013-03-07 215 views
2

路線ASP.NET MVC 4路工作不

routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
    routes.MapRoute(
        name: "Contact", 
        url: "Contact", 
        defaults: new { controller = "Home", action = "Contact" } 
       ); 

我控制器

public class HomeController : BaseController 
    { 
     public ActionResult Contact() 
     { 
      ViewBag.Message = "Your contact page."; 

      return View(); 
     } 
    } 

我的Global.asax

protected void Application_Start() 
     { 
      AreaRegistration.RegisterAllAreas(); 

      WebApiConfig.Register(GlobalConfiguration.Configuration); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 
      AuthConfig.RegisterAuth(); 
     } 

最後我的請求URL

http://localhost:1234/Contact/ 

瀏覽器上的錯誤

無法找到該資源。

描述:HTTP 404.您正在查找的資源(或其中一個 依賴項)可能已被刪除,名稱已更改,或者 暫時不可用。請檢查以下URL並確定 拼寫正確。

請求的URL:/聯繫人/

版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0.30319.18033

我在做什麼錯?

解決方案:

自定義路線應採取優先

routes.MapRoute(
         name: "Contact", 
         url: "Contact", 
         defaults: new { controller = "Home", action = "Contact" } 
        ); 
routes.MapRoute(
        name: "Default", 
        url: "{controller}/{action}/{id}", 
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
       ); 
+0

你的默認路由在哪裏? – ssilas777 2013-03-07 18:39:48

+0

我有它,只是沒有包括在這裏,認爲沒有必要。 – HaBo 2013-03-07 18:42:32

+1

它是自定義路線應該在默認路線上方。 – ssilas777 2013-03-07 18:44:21

回答

13

框架總是試圖將請求的URL匹配到route中加入RouteCollection

路由的順序

所以你應該把自定義路線放在默認路線

//Custom route 
routes.MapRoute(
        name: "Contact", 
        url: "Contact", 
        defaults: new { controller = "Home", action = "Contact" } 
       ); 
//default route 
routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
+0

但隨後調試器在自定義路由中出現問題,並且在啓動時也沒有進入默認路由 – 2014-04-22 10:21:10

+0

@ZaveedAbbasi我不認爲這可能會導致任何問題,如果您發現任何問題,最好用代碼示例提出問題。 – ssilas777 2014-04-22 11:28:44

+0

其實我在...「http://stackoverflow.com/questions/23217271/mvc-routing-with-multiple-parameters-in-not-working/23217364?noredirect=1#comment35517982_23217364」 – 2014-04-22 11:33:40

0
You can use: 

routes.MapRoute(
      name: "Default", 
      url: "{*p}", 
      defaults: new { controller = "Home", action = "Index", p = UrlParameter.Optional } 
     ); 
The asterisk indicates that it's a catch-all route. Keep in mind that these routes are extremely greedy, make sure that this stays below any specific routes. 

You could also add a route constraint to this route which can determine whether the page exists in the database or something.