DevDev
DevDev

Reputation: 11

RouteCreationException: The following errors occurred with attribute routing information

Hello im getting this error when running the API: "Error: The attribute route 'api/Book/{page}/{itemsPerPage}' cannot contain a parameter named '{page}'. Use '[page]' in the route template to insert the value ''."

  [HttpGet("{page}/{itemsPerPage}", Name = "GetBookWithPagination")]
    [ProducesResponseType(404)]
    [ProducesResponseType(400)]
    [ProducesResponseType(200, Type = typeof(PaginationResult<Book>))]
    public async Task<ActionResult<PaginationResult<Book>>> Get(int page, int itemsPerPage, string filter)
    {
        try
        {
            var result = new PaginationResult<Book>();
            result = bookRepo.RetrieveBookWithPagination(page, itemsPerPage, filter);
            return result;
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

The API is working when removing this code block

Upvotes: 1

Views: 3327

Answers (1)

Yanga
Yanga

Reputation: 3012

When using ASP.NET Core MVC Razor Pages, {page} becomes what is effectively a reserved word, just as {controller} and {action} are when working with traditional MVC controllers and actions. In order to work around this, you can simply use something else to represent the page number desired when performing pagination.

For example:

 [HttpGet("{pageIndex}/{itemsPerPage}", Name = "GetBookWithPagination")]
    [ProducesResponseType(404)]
    [ProducesResponseType(400)]
    [ProducesResponseType(200, Type = typeof(PaginationResult<Book>))]
    public async Task<ActionResult<PaginationResult<Book>>> Get(int page, int itemsPerPage, string filter)
    {
        try
        {
            var result = new PaginationResult<Book>();
            result = bookRepo.RetrieveBookWithPagination(page, itemsPerPage, filter);
            return result;
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

Upvotes: 1

Related Questions