FromQuery and FromRoute in Asp.net Core

FromQuery and FromRoute in Asp.net Core
While ASP.NET Core’s model binding automatically tries to match action method parameters to different parts of the request (form data, route values, query strings), you can use the [FromQuery] and [FromRoute] attributes to explicitly tell the model binder where to look for specific values.
 
[FromQuery]
Purpose: Instructs the model binder to extract the parameter value from the query string.
Usage: Apply this attribute to action method parameters that you expect to receive values from the query string portion of the URL (the part after the “?”).
Example:
public IActionResult Index([FromQuery] int page) { … }
In this example, the page parameter would be bound to the value of the page query parameter in the URL (e.g., /products?page=3).
 
 
[FromRoute]
Purpose: Instructs the model binder to extract the parameter value from the route data.
Usage: Apply this attribute to action method parameters that you expect to receive values from the route template of the URL.
Example:
[Route(“products/{id}”)]
public IActionResult Details([FromRoute] int id) { … }
In this example, the id parameter would be bound to the value of the id segment in the URL (e.g., /products/123).

Combined Binding:
By using both [FromQuery] and [FromRoute] on different parameters in the same action method, you can effectively bind values from both the query string and route data simultaneously.
 
Notes
Explicit Binding: Use [FromQuery] and [FromRoute] for explicit control over where the model binder gets values for your action method parameters.
Flexibility: You can combine both attributes in the same action to bind from multiple sources.
Default Behavior: Even without these attributes, ASP.NET Core’s model binding will try to intelligently determine the binding source. However, using these attributes makes your code more explicit and less prone to unexpected behavior.
Type Conversion: The model binder automatically attempts to convert values to the appropriate data types for your action method parameters.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply