Back to: ASP.NET Core Tutorials For Beginners and Professionals
Model Binding using FromRoute in ASP.NET Core MVC
In this article, I will discuss How to Use FromRoute to Perform Model Binding in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing FromQuery in ASP.NET Core MVC.
Model Binding Using FromRoute in ASP.NET Core MVC
In ASP.NET Core MVC, the FromRoute attribute is used to specify that an action method parameter should be bound using data from the route of the HTTP request. This means values embedded in the URL path, not the query string or request body. Route values are typically specified using tokens in route templates. For example, in a route like /users/{id}, the {id} is a route token that can be bound to a method parameter. If you go to the definition of FromRouteAttribute, you will see the following signature.
In ASP.NET Core MVC, the BindingSource and the Name property of the FromRoute attribute are essential for controlling how data is parsed and bound to action method parameters.
- BindingSource: BindingSource specifies where the value for a parameter is found. For example, in the context of the FromRouteAttribute, ASP.NET Core uses the BindingSource.Route automatically. This means the system is configured to look for values specifically in the route part of the incoming HTTP request URL.
- Name: The Name property of the FromRoute attribute specifies an alternative name for a route parameter that binds to the action method parameter. This is useful when the name of the route parameter defined in the route template differs from the name of the action method parameter to which it needs to be bound.
Example to understand FromRoute Attribute in ASP.NET Core MVC:
Let’s assume we are building an API to get user details based on their ID. Here is how you can use the FromRoute attribute. First, create a class file with the name User.cs within the Models folder, and then copy and paste the following code. This is a simple model that represents a user.
namespace ModelBindingDemo.Models { public class User { public int Id { get; set; } public string? Name { get; set; } public int Age { get; set; } public string? Mobile { get; set; } } }
Next, create a new Empty MVC controller named UsersController within the Controllers folder and then copy and paste the following code.
using Microsoft.AspNetCore.Mvc; using ModelBindingDemo.Models; namespace ModelBindingDemo.Controllers { public class UsersController : Controller { private List<User> _users; public UsersController() { _users = new List<User>() { new User(){Id =1, Name ="Pranaya", Age = 35}, new User(){Id =2, Name ="Priyanka", Age = 30}, new User(){Id =3, Name ="Anurag", Age = 35}, new User(){Id =4, Name ="Prateek", Age=30}, new User(){Id =5, Name ="Hina", Age=35} }; } [HttpGet] [Route("users/{Id}/getdetails")] public IActionResult GetUserById([FromRoute] int Id) { // Here, you can use the 'id' to fetch user details from a database or other data sources. var user = _users.FirstOrDefault(x => x.Id == Id); if (user == null) { return NotFound(); } return Ok(user); } } }
When you want to fetch a user with ID 2, you will access the URL: users/2/getdetails. The 2 in the URL would be bound to the Id parameter in the GetUserById action, which is possible because of the FromRoute attribute.
Using Name Property of FromRoute Attribute:
The Name property of the FromRoute Attribute is used when the name of the route parameter defined in the route template is different from the name of the action method parameter to which it needs to be bound. So, it provides a way to map the route data directly to a method parameter with a different name.
Suppose you have a Route Token Named ID, but in your method, you want to bind it to a parameter named UserId. In this case, you need to use the Name property to map these correctly. For a better understanding, please modify the UsersController as follows:
using Microsoft.AspNetCore.Mvc; using ModelBindingDemo.Models; namespace ModelBindingDemo.Controllers { public class UsersController : Controller { private List<User> _users; public UsersController() { _users = new List<User>() { new User(){Id =1, Name ="Pranaya", Age = 35}, new User(){Id =2, Name ="Priyanka", Age = 30}, new User(){Id =3, Name ="Anurag", Age = 35}, new User(){Id =4, Name ="Prateek", Age=30}, new User(){Id =5, Name ="Hina", Age=35} }; } [HttpGet] [Route("users/{Id}/getdetails")] public IActionResult GetUserById([FromRoute(Name ="Id")] int UserId) { // Here, you can use the 'id' to fetch user details from a database or other data sources. var user = _users.FirstOrDefault(x => x.Id == UserId); if (user == null) { return NotFound(); } return Ok(user); } } }
How Does Model Binding Work with FromRoute Attribute in ASP.NET Core?
The FromRoute attribute is used to bind action method parameters to parameters from the route data in an HTTP request. The process of model binding with FromRoute involves several steps:
- Route Template Matching: When a request is received, ASP.NET Core matches the URL to the route templates defined in your controllers or program configuration. Each segment of the URL defined as a parameter within curly braces ({ }) is parsed as route data.
- Identify the Source: The model binder identifies the route parameters as the data source because the FromRoute attribute applied to the action method parameters makes this possible.
- Match and Bind Parameters: The model binder matches the names of the parameters in the route data with the names of the parameters in your action method. If they match, it binds the values from the route data to those parameters. If a Name property is specified in the FromRoute attribute, it overrides the default matching to use this specified name instead.
- Conversion: The values extracted from the route are converted from strings (as all route data is captured as strings) to the types of the respective parameters in the action method. ASP.NET Core uses built-in type converters for most primitive types.
- Validation: Once the values are bound, any validation attributes applied to the action method parameters are processed. If the validation fails, the errors are added to ModelState.
When Should We Use FromRoute Attribute in ASP.NET Core MVC?
The FromRoute attribute is useful when you want to retrieve data directly from the request URL. The following are some of the scenarios where you can use FromRoute Attribute:
- RESTful APIs: In RESTful API design, resource identifiers are often part of the URL. For example, if you have an API endpoint that fetches a specific user by their ID, the user ID might be part of the route. Using FromRoute lets you directly bind this user ID from the route to a method parameter in your controller.
- Avoiding Query Strings for Mandatory Data: If certain data is essential for the operation of a specific endpoint (like an entity ID in CRUD operations), embedding it in the URL (and using FromRoute to bind it) can be more appropriate than relying on query strings, which are better suited for optional parameters.
- Hierarchy in Data: When you are dealing with hierarchical resources where one resource is a subset of another, using route data is more semantically correct. For example, accessing comments on a blog post might look like /posts/123/comments/456, where both 123 and 456 can be bound using FromRoute.
When Not to Use FromRoute?
- Query-Specific Data: If the data represents filters, sorts, or other query-specific data, it might be better suited for the query string (i.e., use FromQuery).
- Large or Complex Data: Route data should be kept simple and limited to identifiers or other small data bits. If you are passing complex objects, those should likely be sent in the request body (i.e., use FromBody).
- Sensitive Data: Don’t send sensitive information in the URL, even if it’s in the route. URLs can be logged, cached, or shared, which could expose sensitive information.
In the next article, we will discuss How to Use FromHeader to Perform Model Binding in ASP.NET Core MVC with Examples. In this article, I explain How to use FromRoute to Perform Model Binding in ASP.NET Core MVC with Examples. I hope you enjoy this FromRoute in ASP.NET Core MVC article.