I have the following situation
[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
is an instance of type GetFooBindModel
. And I am getting
InvalidOperationException: No route matches the supplied values.
I also tried changing the line
return CreatedAtRoute("GetFoo", new { id = getBindModel.Id }, getBindModel);
to
return CreatedAtRoute("api/Foo/GetFoo", new { id = getBindModel.Id }, getBindModel);
but still the same error.
Routing uses a pair of middleware, registered by UseRouting and UseEndpoints: UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app, and selects the best match based on the request. UseEndpoints adds endpoint execution to the middleware pipeline.
CreatedAtRoute (object routeValues, object value) By default, if no information about target route is passed, it will take the path of the current method and use it for creating Location header.
UseEndpoints in ASP.NET Core 3.0 MVC. Routing takes advantage of a pair of middleware components that are registered using the UseRouting and UseEndpoints extension methods. While the former is used to match a request to an endpoint, the latter is used to execute a matched endpoint.
Match the name of your action method (Get) in the FooController with the route name on HttpGet Attribute. You can use the nameof keyword in c#:
[HttpGet("{id}", Name = nameof(Get))]
public ActionResult<FooBindModel> Get([FromRoute]Guid id)
{
...
}
and also Instead of hard coding route name use nameof again:
return CreatedAtRoute(nameof(FooController.Get), new { id = getBindModel.Id }, getBindModel);
and Try again;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With