Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.1 Routing - CreatedAtRoute - No route matches the supplied values

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.

like image 665
john Avatar asked Aug 28 '18 17:08

john


People also ask

How Routing works in ASP net Core?

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.

What is CreatedAtRoute?

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.

What is UseEndpoints in ASP net Core?

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.


1 Answers

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;

like image 171
Armin Torkashvand Avatar answered Oct 02 '22 11:10

Armin Torkashvand