Asp.Net核心MVC - 路由问题

问题描述 投票:1回答:1

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();
    }
}

工作...但我不想为每个动作处理路线...这应该是一个非常大的系统......事情可能会像这样疯狂......

asp.net-mvc routing
1个回答
2
投票

由于您使用Route属性修饰控制器,因此将不会实际使用您在路由表中定义的规则。以下是Routing to Controller Actions文章的引用:

操作按常规路由或属性路由。在控制器或操作上放置路由使其属性路由。

因此,要解决您的问题,只需从[Route("posts")]中删除PostsController属性即可。

© www.soinside.com 2019 - 2024. All rights reserved.