Model Binding using FromRoute in ASP.NET Core MVC

Model Binding using FromRoute in ASP.NET Core MVC

I will discuss How to Use FromRoute to Perform Model Binding in ASP.NET Core MVC with Examples in this article. 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 a 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.

Model Binding Using FromRoute in ASP.NET Core MVC

The FromRouteAttribute specifies that a parameter or property should be bound using route data from the current request.

Example to understand FromRouteAttribute in ASP.NET Core MVC:

Let’s assume we’re building an API to get user details based on their ID. Here’s 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 controller named UsersController and copy and paste the following code into it.

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.

Points to Remember:
  • If the route token’s name (e.g., {Id}) matches the action method’s parameter name (int Id), then we don’t need to specify the FromRoute attribute. ASP.NET Core’s default model binding behavior will automatically bind the value from the route. However, using the attribute can make the intention clear, which can be helpful for readability and maintainability.
  • You can have multiple route parameters in a single route. For example, for a route like /products/{categoryId}/items/{itemId}, you can have two parameters: categoryId and itemId.
  • Always ensure proper validation and error handling, especially when dealing with data that comes from the client, like route parameters. This helps to prevent issues like invalid data or potential security vulnerabilities.
When to Use FromRoute Attribute in ASP.NET Core MVC?

In ASP.NET Core MVC, the FromRoute attribute binds a parameter to a segment of the request’s route. This is a powerful feature when building RESTful APIs or any web service that relies on URL patterns to extract meaningful data about the request. Here’s when you would typically use the FromRoute attribute:

Resource Identifiers in RESTful APIs:

One of the core principles of RESTful design is that resources have unique URIs. Often, these resources’ identifiers (like an ID) are passed as part of the route.

/users/{userId}
/products/{productId}/reviews
Hierarchical Data or Relationships:

When you have a hierarchical or relational structure between resources, route parameters can represent this structure.

/authors/{authorId}/books/{bookId}

Versioning APIs:

Some APIs use URI versioning, where the version of the API is specified as a segment of the route.

/v1/users/{userId}
/v2/users/{userId}
Friendly URLs and Slugs:

For SEO purposes or improved user experience, many websites use descriptive slugs instead of or in addition to numerical IDs.

/articles/{articleSlug}
/events/{eventName}
When Not to Use:
  • 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 limited to identifiers or other small data bits. If you’re passing complex objects, those should likely be sent in the request body (i.e., use FromBody).
  • Sensitive Data: It’s generally a bad practice to put sensitive information in the URL, even if it’s in the route. URLs can be logged, cached, or shared, which could expose sensitive information.

So, FromRoute provides an intuitive and RESTful way to capture and use data from the URL path, making it a core feature for many web APIs and applications.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *