0

I'm currently working with the web api in .NET Core 3.1 and I'm working with many GET requests that works with pagination (the client sends a request to get items, provides the page number, amount per items, etc, then receives the items).

I noticed that when I want to use this pagination option, it's creating sort of code duplication (every time I need to put this specific code: [FromQuery] page, [FromQuery] perPage). I was wondering if there is a way to define those parameter in one specific option and then use it wherever I need. That way I will prevent code duplication and it will be much easier if I'll ever make changes to the pagination system.

EDIT: the page and perPage parameters are ints.

2
  • What is the Type of page and perPage variables? Commented Jun 2, 2022 at 9:33
  • My bad, forgot to mention those types - Simple int parameters. Commented Jun 2, 2022 at 9:38

1 Answer 1

2

Define a class with all property needs for pagination

public class QueryParam
{
   public int Page {get; set;}
   public int PerPage {get; set;}
}

Then use that class in controller's methods

public async Task<IActionResult> GetSomething([FromQuery] QueryParam query)
{
   return Ok();
}

Sign up to request clarification or add additional context in comments.

1 Comment

Seems to work great. I've tried to do the same with struct before opening the question and it just threw an exception but with class it's working, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.