Why can the second specified Route not be matched? (note, it seems to
make no difference which order the Routes were specified)
我能做些什么来帮助/加强我期望的匹配?
Well, based on your scenario and description, the behavior you re observing is due to the way route matching works in ASP.NET Core. When you specify multiple route templates, the routing system tries to match incoming requests to those templates in the order they are declared.
根据你的代码,由于RedirectToAction试图根据你提供的路线价值对目标行动路线模板进行匹配,因此出现了意想不到的查询代码?。
While you supply ID1 = b
and ID2 = a
, it first finds a match with the template {ID1}/Redirected
, resulting in /b/Redirected
.
However, it then sees the additional ID2 value that doesn t fit this template, so it appends it as a query string.
为了实现你想要的行为,你需要更明确地说明使用哪条路线模板。 你们可以通过向每个路线模板提供具体路线名称来做到这一点,然后在重新定位时具体说明路线名称。
您可以认为:
public class TestController : Controller
{
[Route("{ID1}/Test", Name = "TestRoute1")]
[Route("{ID2}/{ID1}/Test", Name = "TestRoute2")]
public IActionResult Test(string id1, string id2)
{
return RedirectToAction("Redirected", new { ID1 = id1, ID2 = id2 });
}
[Route("{ID1}/Redirected", Name = "RedirectedRoute1")]
[Route("{ID2}/{ID1}/Redirected", Name = "RedirectedRoute2")]
public string Redirected()
{
return "Redirected";
}
}
现在,在重新定位时,明确指明路线名称如下:
return RedirectToAction("Redirected", "Test", new { ID1 = id1, ID2 = id2 }).WithRouteName("RedirectedRoute1");
In addition, you also could consider attribute routing.Because, it provides clearer and more fine-grained control over route mapping.
[HttpGet("{ID2}/{ID1}/Redirected")]
public string Redirected() { ... }
<>说明: <https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnet-8.0#conventional-routing-order”rel=“nofollow noretinger”>refered to this official document> for