我有以下情况
[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:没有路由与提供的值匹配。
我也试过换线
return CreatedAtRoute("GetFoo", new { id = getBindModel.Id }, getBindModel);
至
return CreatedAtRoute("api/Foo/GetFoo", new { id = getBindModel.Id }, getBindModel);
但仍然是同样的错误。
将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);
然后再试一次;