Passing multiple parameters to a GET method in C# is a common requirement in web API development. This article explores various techniques for achieving this within ASP.NET Core, focusing on clarity, maintainability, and best practices.
Table of Contents
- Passing Parameters via Conventional Routing
- Using Attribute Routing and [FromQuery]
- Handling Optional Parameters
- Leveraging Model Binding
- Robust Error Handling
Passing Parameters via Conventional Routing
Conventional routing directly incorporates parameters into the URL path. This approach is suitable for a small number of parameters that directly identify a resource.
Example: Retrieving a product based on its ID and category ID.
URL: /products/123/category/456
using Microsoft.AspNetCore.Mvc;
public class ProductsController : Controller
{
public IActionResult GetProduct(int productId, int categoryId)
{
// Process productId and categoryId
return Ok($"Product ID: {productId}, Category ID: {categoryId}");
}
}
Limitations: URLs become less readable and maintainable as the number of parameters grows. It’s less flexible for optional parameters.
Using Attribute Routing and [FromQuery]
Attribute routing provides greater control over URL structure. Using [FromQuery]
, parameters are extracted from the query string, making URLs cleaner and more manageable, even with numerous parameters.
Example: The same product retrieval example, but using attribute routing and [FromQuery]
.
URL: /products?productId=123&categoryId=456
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProduct([FromQuery] int productId, [FromQuery] int categoryId)
{
return Ok($"Product ID: {productId}, Category ID: {categoryId}");
}
}
This method promotes better URL organization and readability. The [ApiController]
attribute enables automatic model validation and response handling.
Handling Optional Parameters
Optional parameters enhance flexibility. Use default values within the controller action signature.
[HttpGet]
public IActionResult GetProduct([FromQuery] int productId, [FromQuery] int categoryId, [FromQuery] int pageSize = 10)
{
return Ok($"Product ID: {productId}, Category ID: {categoryId}, Page Size: {pageSize}");
}
Here, pageSize
defaults to 10 if not provided in the query string.
Leveraging Model Binding
For multiple parameters, consider creating a dedicated model. This improves code organization and maintainability. ASP.NET Core will automatically bind the query string to the model’s properties.
public class ProductFilter
{
public int ProductId { get; set; }
public int CategoryId { get; set; }
public int PageSize { get; set; } = 10;
}
[HttpGet]
public IActionResult GetProduct(ProductFilter filter)
{
return Ok($"Product ID: {filter.ProductId}, Category ID: {filter.CategoryId}, Page Size: {filter.PageSize}");
}
Robust Error Handling
Always handle potential errors, such as missing required parameters or invalid data types. Use techniques like model validation or explicit parameter checks to gracefully handle these situations.
[HttpGet]
public IActionResult GetProduct(ProductFilter filter)
{
if (filter.ProductId == 0)
{
return BadRequest("Product ID is required.");
}
// ... rest of your logic ...
}