Search code examples
.net-coreasp.net-web-api-routingwebapi

.Net Core Web API Post route endpoint not being hit


I have the following .Net Core API route defined.

[HttpPost("/addproduct")]
[Consumes("application/json")]
public ActionResult<IEnumerable<ProductDTO>> AddProduct([FromBody] ProductDTO){}

I already have the following attributes defined on the class:

[EnableCors()]
[Produces("application/json")]
[Route("api/[controller]")]

I am calling it like this: https://localhost:xxxxx/api/products/addproduct and I'm passing a payload to it that represents the productDTO. Why does this route not get hit?


Solution

  • The issue is with the routing attribute used on the HttpPost.

    As defined above, the AddProduct action method matches the following url:

    https://localhost:xxxx/addproduct
    

    Even though you're using token replacement for the controller name,by using a leading slash you're overriding that route on the AddProduct method.

    To properly route to the method remove the leading slash like this:

        [HttpPost("addproduct")]
        [Consumes("application/json")]
        public ActionResult<IEnumerable<ProductDTO>> AddProduct([FromBody] ProductDTO productDto)
    

    For more information regarding attribute routing or controller routing in general read this page on Microsoft Docs