I assume you are familiar with MVC5 and its various features. One of the interesting features of MVC5 is attribute routing. We understand routing in MVC; we can say it is the most important feature of the Model, View and Controller design pattern. It shows the real beauty of separation of concerns. In all previous versions of MVC, we saw that the routing mechanism is defined in one place, basically it's in the “RouteConfig.cs” file.
It's great to keep all the routing information in one place to make it centralized. But the problem is that if we declare a routing mechanism in this way, then all the actions and the controller will follow the same routing technique. Now if we wanted to define a different routing to a different controller then we need to implement attribute routing.
Using attribute routing we can define various routing techniques for different controllers, so the user will get more freedom to use the application.
Since this is called attribute routing, we will use the Route() attribute to the action. In this example, we defined two actions and we have specified a route above this.
The first products() action will execute when we browse to the following URL.
http://localhost:2968/products/shirt
And if we want to invoke a second action then we need to browse to the following URL.
http://localhost:2968/products/shirt/10
Now, to enable attribute routing we need to enable it in the Route.Config.cs file. Just add the following single line of code.
Here is sample code to execute.
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MVC_5.App_Data;
- namespace MVC_5.Controllers
- {
- public class testController : Controller
- {
- [Route("products/shirt")]
- public void products()
- {
- }
- [Route("products/shirt/{id}")]
- public void products(int id)
- {
- }
- }
- }


TwostepdevelopersPosted Jul 23, 2019, 5:36 AM
If we have complex data to pass it as object then we can do it like [HttpPost,Route("Manage/GetAllInvoices")] public async Task<ActionResult> GetAllInvoices(DataTablesParam param)