【问题标题】:Asp.Net Core MVC - Routing IssueAsp.Net Core MVC - 路由问题
【发布时间】:2018-08-11 14:48:22
【问题描述】:

TL;DR;
如何将“http://localhost/posts/1”路由到 PostsController 上的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”确实路由正确......

编辑1:

public class PostsController : Controller
{
    [Route("Posts/{id:int?}"
    public IActionResult Index(int? id)
    {
        return View();
    }
}

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

【问题讨论】:

  • 如果使用字符串而不是 int 是否有效?您可以使用 int.TryParse 将字符串转换为代码中的 int
  • @KenTucker no...同样的问题...我还修复了删除int约束的路线

标签: asp.net-mvc routing


【解决方案1】:

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

动作要么是传统路由,要么是属性路由。配售 控制器上的路由或动作使其属性路由。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2013-11-13
    • 2011-11-30
    • 2013-06-07
    相关资源
    最近更新 更多