默认路由未重定向到mvc中的预期页面

时间:2015-12-25 17:45:48

标签: c# asp.net-mvc asp.net-mvc-4

我有一个HomeController我有2 ActionResultsIndexProjects。现在我的RouteConfig.cs添加了以下路线:

routes.MapRoute(
    name: "Default_1",//Changed this to some other name
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

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

因此,根据上述配置,我希望默认情况下用户将重定向到/Home/Projects。但它又重定向到Index行动。 为什么不重定向到Projects行动?我们这里有多条路线吗?Default名称不会被视为默认网址?

1 个答案:

答案 0 :(得分:2)

注册路线时,请将您的特定路线定义放在默认路线定义之前。 路线注册的顺序很重要

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

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

使用此配置,任何来的请求都将重定向到您的Home/Projects,因为网址格式仍然是通用格式({controller}/{action}/{id})。所以我猜你真的是这样的。

routes.MapRoute(
    name: "Project",
    url: "projects/{id}",
    defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);    

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

这会将请求http://yourSite.com/Projects发送到Home/Projects

或者您可以使用属性路由在Projects控制器中定义此路由模式。要启用属性路由,您可以使用MapMvcAttributeRoutes RegisterRoutes方法调用RouteConfig.cs方法。您仍将保留默认路由定义。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapMvcAttributeRoutes();

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

    );
}

在您的ProjectsController中

[Route("Projects/{id?}")]
public ActionResult Index(int? id)
{
   //check id value  and return something
}