MVC路由参数未被传递

问题描述 投票:1回答:3

我正在尝试做一些MVC路由,遵循在线教程,但由于某种原因路由不起作用。

我想做http://www.website.com/news/news-title

我想要做的路线如下。

routes.MapRoute(
    "News",
    "{controller}/{url}",
    new { controller = "News", action = "Index", url = "" }
);

在我的NewsController中,我有以下ActionResult。

public ActionResult Index(String url)
{
    return View();
}

但是,当单步执行代码时,url不会被填充。

谢谢

==更新==

谢谢大家的回复。

我没有修改下面的路线

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

        routes.Add(new SubdomainRoute());

        routes.MapRoute(
            "News",
            "News/{action}/{slug}",
            new { controller = "News", action = "Index" }
        );

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

此URL有效:/news/index/?slug=test-news-title

但是这个URL不是:/news/index/test-news-title

===进一步编辑===

看来我的子域路线正在弄乱它。如果我删除子域路由它工作正常。

谢谢。

c# asp.net-mvc url-routing asp.net-mvc-routing
3个回答
1
投票

最有可能的是,您的路线过于宽泛。但这取决于其他路由的配置方式。您需要发布整个路线配置(包括区域路线和属性路线),以便合理地得到您的路线有问题的答案。

但是,您可以更加具体地使用此路线,因为您知道它需要从/News开始。

routes.MapRoute(
    "News",
    "News/{url}",
    new { controller = "News", action = "Index" }
);

此外,通过提供默认值使URL参数可选是没有意义的。如果删除url = "",则URL中需要url参数。如果配置如上,如果您只是传递/News,它将不匹配此路线。但是,正如您所拥有的,此URL将匹配。

最后,确保此路线按正确的顺序排列。它应该放在您的默认路线之前(如果您还有)。


0
投票

您已为参数url设置空字符串。你应该使用UrlParameter.Optional(如果是强制性的话,可以删除它):

routes.MapRoute(
    "News",
    "{controller}/{url}",
    new { controller = "News", action = "Index", url = UrlParameter.Optional }
);

0
投票

你错过了MapRoute中的动作部分

routes.MapRoute(
    "News",
    "{controller}/{action}/{url}",
    new { controller = "News", action = "Index", url = "" }
);

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.