2013-03-07 156 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.