【问题标题】:ASP.NET MVC MapRoute more than 1 parameter issueASP.NET MVC MapRoute 超过 1 个参数问题
【发布时间】:2018-08-08 17:48:12
【问题描述】:

我正在尝试将MapRoute 与多个参数一起使用,但它无法正常工作。

我的RegisterRoutes

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

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    routes.MapRoute(
        "TestRoute",                                              // Route name
        "{controller}/{action}/{id}/{tID}",                           // URL with parameters
        new { controller = "Test", action = "Index", id = "", tID = "" }  // Parameter defaults
    );
}

我的测试控制器:

public class TestController : Controller
{
    public ActionResult Index(int? id, int? tID)
    {
        // Some code to create viewModel

        return View(viewModel);
    }
}

我从Html.ActionLink 调用此方法:

@Html.ActionLink(@item.Description, "Index", "Test", 
    new { id = @item.CatID, tID = @item.myTID }, null)

但是,它返回的 url 为:/Test/Index/3?tID=264981 而不是 /Test/Index/3/264981

有人知道我做错了什么吗?

【问题讨论】:

  • 更具体的路线需要先。
  • 按照佩德罗所说的去做。首先是TestRoute 路由,然后是Default 路由。
  • 有效!谢谢

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


【解决方案1】:

这里有几个问题:

  1. 应先注册更具体的路线,然后再注册一般路线。
  2. 由于第一场比赛总是获胜,因此需要以某种方式约束路线。例如,让在路由 B 之前注册的路由 A 不匹配应该由路由 B 处理的案例。
  3. 最合乎逻辑的行为通常是将路由值设为必需,而不是可选的。


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

    // Register the most specific route first
    routes.MapRoute(
        "TestRoute",

        // Constrain the URL - the simplest way is just to add a literal
        // segment like this, but you could make a route constraint instead.
        "Test/{action}/{id}/{tID}", 

        // Don't set a value for id or tID to make these route values required.
        // If it makes sense to use /Test/Action without any additional segments,
        // then setting defaults is okay.
        new { controller = "Test", action = "Index" }  
    );

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

参考:Why map special routes first before common routes in asp.net mvc?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多