parametros-de-accion-aspnet

Action Parameters in ASP.NET

  • 4 min

Action methods can receive parameters that we can pass from the HTTP request (from different sources).

For example, values can come from the URL, query parameters, or the request body.

To convert request data into parameters, ASP.NET uses a process called model binding, which does all the work without us having to worry about it.

  1. Identifies available sources (query string, route data, body)
  2. Converts data to the required type
  3. Assigns values to the parameters

This assignment is automatic, which greatly simplifies data handling for us and avoids having to write repetitive code and the possibility of making errors.

Types of parameters

As we said, ASP.NET can convert data received from different sources of the HTTP request into parameters.

TypeRecommended UseExampleAttribute in ASP.NET Core
RouteUnique IDs, specific resources/api/products/5[FromRoute]
QueryFilters, pagination, sorting/api/products?category=tech&page=2[FromQuery]
BodyCreation/update (JSON/XML)POST /api/products + JSON[FromBody]
HeadersAuthentication, metadataAuthorization: Bearer xyz[FromHeader]
FormsFile uploads or form dataContent-Type: multipart/form-data[FromForm]

Let’s look at each one in detail 👇,

Route Parameters

Route parameters (or route parameters) are part of the URL itself, making them ideal for identifying unique resources, such as a user or a product.

For example, in /products/5, the 5 is a route parameter that likely represents an ID.

In ASP.NET, we define these parameters directly in the route template:

[HttpGet("products/{id}")]
public IActionResult GetProduct(int id)
{
    var product = _productService.GetById(id);
    return Ok(product);
}
Copied!

The placeholder {id} in the route indicates we expect a numeric value, which ASP.NET automatically converts to the int type of the method’s parameter.

When to use route parameters

  • Unique identifiers (like database IDs).
  • Mandatory data for the operation.
  • Hierarchical structures (e.g., /departments/{deptId}/employees/{empId}).

Do not use route parameters for optional data or complex filters, as they clutter the URL and make it harder to read.

Query Parameters

Query parameters (query parameters) appear after the ? in the URL and are ideal for optional data, such as filters, pagination, or sorting. For example: /products?category=electronics&page=2.

In ASP.NET, these parameters are defined as method arguments:

[HttpGet("products")]
public IActionResult GetProducts(
    [FromQuery] string category, 
    [FromQuery] int page = 1)
{
    var filteredProducts = _productService.GetByCategory(category, page);
    return Ok(filteredProducts);
}
Copied!

The [FromQuery] attribute is optional, but it helps clarify the intent. Parameters can have default values (like page = 1).

Best practices with query parameters

  • Use descriptive names (category instead of cat).
  • Avoid complex structures (use the body for that).
  • Consider pagination (page, pageSize) in endpoints that return collections.

Body Parameters

The request body (request body) is mainly used in POST, PUT, and PATCH operations to send structured data, such as a JSON object. For example, when creating a new product:

[HttpPost("products")]
public IActionResult CreateProduct([FromBody] ProductDto productDto)
{
    var createdProduct = _productService.Create(productDto);
    return CreatedAtAction(nameof(GetProduct), new { id = createdProduct.Id }, createdProduct);
}
Copied!

The [FromBody] attribute indicates that ASP.NET should deserialize the received JSON into a ProductDto object.

Key rules for the body

  • Avoid sending IDs in the body for update operations (better use routes).

Form Parameters

Form parameters are used to receive data sent from HTML forms. This data is sent in the request body and can be bound to action parameters.

[HttpPost("products/create")]
public IActionResult Create([FromForm] Product product)
{
    // Logic to create a new product
    CreateProduct(product);
    return RedirectToAction("Index");
}
Copied!

Header Parameters*

Header parameters are extracted from HTTP headers. For this, the [FromHeader] attribute is used.

[HttpGet("products")]
public IActionResult List([FromHeader(Name = "Accept-Language")] string language)
{
    // Logic to list products according to the language
    var products = ListProductsByLanguage(language);
    return View(products);
}
Copied!