c# - ASP.NET Core 2.1 路由 - CreatedAtRoute - 没有路由与提供的值匹配

标签 c# .net asp.net-core asp.net-core-2.1

我有以下情况

[Route("api/[controller]")]
[ApiController]
public class FooController: ControllerBase
{
    [HttpGet("{id}", Name = "GetFoo")]
    public ActionResult<FooBindModel> Get([FromRoute]Guid id)
    {
        // ...
    }
}

[Route("api/[controller]")]
[ApiController]
public class Foo2Controller: ControllerBase
{

    [HttpPost("/api/Foo2/Create")]
    public ActionResult<GetFooBindModel> Create([FromBody]PostFooBindModel postBindModel)
    {
        //...
        return CreatedAtRoute("GetFoo", new { id = getBindModel.Id }, getBindModel);

    }
}

PS:getBindModel 是类型GetFooBindModel 的一个实例。我越来越

InvalidOperationException: No route matches the supplied values.

我也试过改线

return CreatedAtRoute("GetFoo", new { id = getBindModel.Id }, getBindModel);

return CreatedAtRoute("api/Foo/GetFoo", new { id = getBindModel.Id }, getBindModel);

还是一样的错误

最佳答案

FooController 中的操作方法 (Get) 的名称与 HttpGet 属性上的路由名称相匹配。你可以在 c# 中使用 nameof 关键字:

[HttpGet("{id}", Name = nameof(Get))]
public ActionResult<FooBindModel> Get([FromRoute]Guid id)
{
          ...
}

并且再次使用 nameof 而不是硬编码路由名称:

return CreatedAtRoute(nameof(FooController.Get), new { id = getBindModel.Id }, getBindModel);

再试一次;

关于c# - ASP.NET Core 2.1 路由 - CreatedAtRoute - 没有路由与提供的值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52063794/

相关文章:

c# - 是否有可能为 windows 8 开发一个 .Net 应用程序,它也适用于 windows 7 和 Vista

c# - String.Trim() 删除的所有字符的列表?

c# - 为什么我们不能从 EntityObject 获取 ObjectContext

c# - 使用 .NET CORE 3.1 进行 SFTP 下载

docker - ASP.NET Core 2.0 在 Kubernetes 中启动 Kestrel 时出错

entity-framework - 未找到与命令 "dotnet-ef"匹配的可执行文件

c# - 以编程方式注销 ASP.NET 用户

c# - 在winforms中填充一个巨大的对象

c# - 复制粘贴后台工具

c# - Azure DevOps VSTS .netcore 构建失败,但在我的电脑上运行良好