【问题标题】:MVC Routing Parameter Not Being Passed未传递 MVC 路由参数
【发布时间】:2016-03-18 12:53:48
【问题描述】:

我正在尝试按照在线教程进行一些 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 }
        );
    }

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

但是这个网址没有:/news/index/test-news-title

=== 进一步编辑 ===

看来我的子域路由搞砸了。如果我删除子域路由它工作正常。

谢谢。

【问题讨论】:

  • slug 是个好名字!
  • 那么,您也可以发布您的子域路由吗?确保它在与传入请求不匹配的情况下返回null,否则路由框架将不会检查您的任何其他路由。第一场比赛总是赢。

标签: c# asp.net-mvc url-routing asp.net-mvc-routing


【解决方案1】:

很可能,您的路线过于宽泛。但这取决于其余路线的配置方式。您需要发布您的整个路线配置(包括区域路线和属性路线),以便合理地回答您的路线有什么问题。

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

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

另外,通过提供默认值使 URL 参数成为可选参数可能没有意义。如果删除 url = "",则 URL 中需要 url 参数。如上配置,如果你只是通过/News,它不会匹配这个路由。但是,正如您所拥有的那样,此 URL 将匹配。

最后,确保这条路线的排列顺序正确。它应该放在之前你的默认路由(如果你还有它的话)。

【讨论】:

    【解决方案2】:

    您已为参数 url 设置了空字符串。您应该改用 UrlParameter.Optional (或者如果是强制性的,则完全删除它):

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

    【讨论】:

      【解决方案3】:

      您缺少MapRoute 中的操作部分

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

      希望有帮助

      【讨论】:

      • 谢谢,但是如何从 url 中删除 /Index/?
      • 如果 OP 不希望 URL 中的操作,则此答案没有帮助。提供action = "Index" 的默认值足以使其与操作匹配。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      相关资源
      最近更新 更多