TL; DR;
如何在PostsController上将“http://localhost/posts/1”路由到public IActionResult Index(int? id)
?
半长版: 我的路线定义为:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "posts",
template: "Posts/{id:int?}",
defaults: new { controller = "Posts", action = "Index" });
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id:int?}");
});
我的帖子控制器是:
[Route("posts")]
public class PostsController : Controller
{
public IActionResult Index(int? id)
{
return View();
}
}
问题是“http://localhost:5432/posts”工作正常但“http://localhost:5432/posts/1”确实正确路由...
EDIT1
public class PostsController : Controller
{
[Route("Posts/{id:int?}"
public IActionResult Index(int? id)
{
return View();
}
}
工作...但我不想为每个动作处理路线...这应该是一个非常大的系统......事情可能会像这样疯狂......
由于您使用Route
属性修饰控制器,因此将不会实际使用您在路由表中定义的规则。以下是Routing to Controller Actions文章的引用:
操作按常规路由或属性路由。在控制器或操作上放置路由使其属性路由。
因此,要解决您的问题,只需从[Route("posts")]
中删除PostsController
属性即可。