ASP.NET MVC MapRoute超过1个参数问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET MVC MapRoute超过1个参数问题相关的知识,希望对你有一定的参考价值。
我正在尝试使用带有多个参数的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
有人知道我做错了什么吗?
答案
这里有几个问题:
- 应在一般路线之前先注册更具体的路线。
- 由于第一场比赛总是胜利,因此需要以某种方式约束路线。例如,保持在路由B之前注册的路由A匹配应由路由B处理的情况。
- 最符合逻辑的行为通常是使所需的路由值,而不是可选的。
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?
以上是关于ASP.NET MVC MapRoute超过1个参数问题的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core 2.2 MVC MapRoute 项目到 ASP.NET 3.0 端点 MapAreaControllerRoute “找不到此本地主机页面”