在 ASP.Net Core 2 中使用标签助手生成一个不错的 URL
Generating a nice URL with tag helpers in ASP.Net Core 2
如何使用标签助手生成漂亮的 URL?
例如:
<a asp-controller="Article"
asp-action="FilterByTag"
asp-route-tagId="@tag.Id"
title="@tag.Description">
<span class="badge badge-dark">@tag.Title</span>
</a>
此代码生成 URL 类似 /Article/FilterByTag?tagId=2
但我想要 /Article/FilterByTag/tagId=2
或 /Article/FilterByTag/2
如何使用标签助手生成此 URL?
在 [Route("Article/FilterByTag/{tagId}")]
这样的操作上使用属性路由
或者例如
[Route("[controller]")]
public class ArticleController : Controller {
//...other actions
[HttpGet]
[Route("FilterByTag/{tagId}")] // Matches GET Article/FilterByTag/2
public IActionResult FilterByTag(int tagId) {
//...
return View();
}
}
这样,当标签助手引用动作时,生成的 link 将映射到动作的路由模板和 return 所需的格式,如 Article/FilterByTag/2
Attribute routing requires more input to specify a route; the conventional default route handles routes more succinctly. However, attribute routing allows (and requires) precise control of which route templates apply to each action.
如何使用标签助手生成漂亮的 URL?
例如:
<a asp-controller="Article"
asp-action="FilterByTag"
asp-route-tagId="@tag.Id"
title="@tag.Description">
<span class="badge badge-dark">@tag.Title</span>
</a>
此代码生成 URL 类似 /Article/FilterByTag?tagId=2
但我想要 /Article/FilterByTag/tagId=2
或 /Article/FilterByTag/2
如何使用标签助手生成此 URL?
在 [Route("Article/FilterByTag/{tagId}")]
或者例如
[Route("[controller]")]
public class ArticleController : Controller {
//...other actions
[HttpGet]
[Route("FilterByTag/{tagId}")] // Matches GET Article/FilterByTag/2
public IActionResult FilterByTag(int tagId) {
//...
return View();
}
}
这样,当标签助手引用动作时,生成的 link 将映射到动作的路由模板和 return 所需的格式,如 Article/FilterByTag/2
Attribute routing requires more input to specify a route; the conventional default route handles routes more succinctly. However, attribute routing allows (and requires) precise control of which route templates apply to each action.