我在asp.net core 2.1中尝试了一些路由,但是遇到路由问题...
Startup.cs->配置方法
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{Controller=Demo}/{Action=Index}/{id?}");
});
DemoController.cs
[Route("demo")]
public class DemoController : Controller
{
[Route("")]
[Route("index")]
[Route("MyDemoPage")]
[Route("~/")]
public IActionResult Index()
{
return View();
}
[Route("demo2/{id}")]
[Route("cj/{id}")]
public IActionResult Demo2(int id)
{
ViewBag.id = id;
return View("Demo2");
}
[Route("demo3/{id1}/{id2}")]
[Route("cc/{id1}/{id2}")]
public IActionResult Demo3(int id1,string id2)
{
ViewBag.id = id1;
ViewBag.id2 = id2;
return View("Demo3");
}
}
Index.cshtml页面
@*[Route("demo2/{id}")]*@
<br />
<a asp-controller="demo" asp-action="demo2" asp-route-id="123">Demo2</a>
@*Above Tag renders :> <a href="/demo/cj/123">Demo2</a>*@ Link 1
<br />
@*[Route("cj/{id}")]*@
<br />
<a asp-controller="demo" asp-action="cj" asp-route-id="07">Demo2 via route CJ</a>
@*Above Tag renders :> <a href="/demo/cj/07">Demo2 via route CJ</a>*@ Link 2
<br />
@*[Route("demo3/{id1}/{id2}")]*@
<br />
<a asp-controller="demo" asp-action="demo3" asp-route-id1="123" asp-route-id2="P001">Demo3</a>
@*Above Tag renders :> <a href="/demo/cc/123/P001">Demo3</a>*@ Link 3
<br />
@*[Route("cc/{id1}/{id2}")]*@
<br />
<a asp-controller="demo" asp-action="cc" asp-route-id1="123" asp-route-id2="abc">Demo via CC</a>
@*Above Tag renders :> <a href="/demo/cc?id1=123&id2=abc">Demo via CC</a>*@ Link 4
Demo2.cshtml
@*[Route("index")]*@
<br />
<a asp-controller="demo" asp-action="index">Index Page</a>
@*Above Tag renders :> <a href="/demo/MyDemoPage">Index Page</a>*@ Link 5
<br />
@*[Route("MyDemoPage")]*@
<br />
<a asp-controller="demo" asp-action="MyDemoPage">Index Page via MyDemoPage
Route</a>
@*Above Tag renders :> <a href="/demo/MyDemoPage">Index Page via MyDemoPage
Route</a>*@ Link 6
我很困惑为什么链接4和链接3在index.cshtml和 链接5和链接6呈现相同的href 请帮助...
答案 0 :(得分:2)
由于链接5和链接6 的结果不同,因此它们是由不同的规则生成的。
要生成URL,请RouteCollection
调用GetVirtualPath以使用IRouter
生成URL。有两个默认的irouter,Microsoft.AspNetCore.Mvc.Internal.AttributeRoute
和Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler
。
对于asp-action="index"
,它由AttributeRoute
处理,GetMatches将在MyDemoPage
之前对index
进行排序。您可以检查OutboundMatchResultComparer 来检查比较逻辑。如果将[Route("MyDemoPage")]
更改为[Route("myDemoPage")]
,它将生成 / demo / index 。
对于asp-action="MyDemoPage"
,GetMatches
返回IList<OutboundMatchResult>
的零计数。然后,它转到MvcRouteHandler
,并调用RouteBase
。 _binder.BindValues(values.AcceptedValues);将生成 / demo / MyDemoPage 。
GetMatches
的不同结果由控制器动作中是否存在asp-action
的值控制。对于您的情况,Index
存在,但MyDemoPage
不存在,MyDemoPage
没有相应的方法。
更新
再过一次,关键的不同结果是由
action
确实存在于Controller方法中。
对于asp-action="cc"
,cc
中没有DemoController
动作,它与Controller MVC Binder
一起使用,并且格式为/demo/cc?id1=123&id2=abc
。
对于asp-action="demo3"
,有一个名为demo3
的动作,它是由Router Attribute Binder
生成的,将依次生成_template = "demo/cc/{id1}/{id2}"
和_template = "demo/demo3/{id1}/{id2}"
。对于订单,它将返回/demo/cc/123/P001
。