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

问题描述 投票:5回答: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:getBindModelGetFooBindModel类型的一个实例。我正在接受

InvalidOperationException:没有路由与提供的值匹配。

我也试过换线

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

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

但仍然是同样的错误。

c# .net asp.net-core asp.net-core-2.1
1个回答
7
投票

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

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

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

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

然后再试一次;

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