【问题标题】:MVC Route ConfigurationMVC 路由配置
【发布时间】:2016-09-26 00:55:37
【问题描述】:

我的 HomeController 中有以下内容:

public ActionResult Share(string id)
{
    Debate debate;
    try
    {
        debate = Db.Debates.Single(deb => deb.ShareText.Equals(id));
    }
    catch (Exception)
    {
        return RedirectToAction("Index");
    }
    return View(debate);
}

这允许我以这种方式调用 url:

http://localhost:50499/Home/Share/SomeTextHere

我在 routeconfig 文件中这样配置路由:

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

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

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

我希望能够以这种方式调用 URL:

http://localhost:50499/Debate/SomeTextHere

我一直在努力解决这个问题,但没有运气。实现它的最佳方法是什么?

【问题讨论】:

  • 您不能同时从 url 中删除控制器和操作名称。您的路线需要以某种方式区分。您可以为.../Share/SomeTextHere 创建一条路线
  • 另请注意,您显示的两条路线是相同的 - 它们都匹配包含 2 个段和可选的第 3 段的任何 url。你的第二条路线永远不会被击中(你也可以删除第一条)
  • @StephenMuecke 我把网址改成了localhost:50499/Debate/SomeTextHere 这可能吗?
  • @MRFerocius 您可以将其设置为路由并将默认值设置为您想要的控制器和操作。您希望该网址映射到哪里?
  • 如果你想要../Debate/SomeTextHere然后将第一个路由定义更改为url: "Debate/{id}",

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


【解决方案1】:

正如@StephenMuecke 在 cmets 中提到的,您需要更改路线以使其不那么笼统。

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

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

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

Share 路由现在允许 http://localhost:50499/Debate/SomeTextHere 路由到适当的控制器操作。

【讨论】:

  • 我认为 OP 只想要 ../Debate/xx 所以它的 url: "Debate/{id}",
  • @StephenMuecke 你是对的。我误读了要求。谢谢
猜你喜欢
  • 2017-07-12
  • 2021-04-23
  • 1970-01-01
  • 2015-12-09
  • 2014-01-08
  • 2016-01-07
  • 2016-10-16
  • 2014-12-01
相关资源
最近更新 更多