Sunday, May 26, 2019

Attribute routing in Asp.Net Core MVC

In the previous post we saw about Routing in Asp.Net Core MVC Applications, and how to define Routing in the Applications Startup, this is called conventional routing. Asp.Net Core MVC applications also provide us another way to define routes called Attribute Routing.

Attribute Routing
As the name suggests Attribute Routing is defined by defining routes in action methods using a Route attribute as follows.
   [Route("Home/Index")]
  
public IActionResult Index()
   {
      
return View();
   }


The above attribute routing in the Index method of the Users controller will map the following URL’s to this action method.

http://localhost/UserDetails
http://localhost/UserDetails/Index

similarly we can create attribute routing for the other action methods in the Users controller as follows.

        [Route("UserDetails/Create")]
        public IActionResult Create()
        {
            return View();
        }

        [Route(
"UserDetails/Edit")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var users = await _context.Users.FindAsync(id);
            if (users == null)
            {
                return NotFound();
            }
            return View(users);
        }

        [Route(
"UserDetails/Delete")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var users = await _context.Users
                .FirstOrDefaultAsync(m => m.UserId == id);
            if (users == null)
            {
                return NotFound();
            }

            return View(users);
        }
Attribute routing can also be defined at the controller class level, this will avoid redundancy in specifying the routes for every action method. This way the main route name UserDetails will be defined at the controller level and each action method will specify only the route specific to that action method. The above routes can also be done using the combination of Controller and Action method level routing as follows.

    [Route("UserDetails")]
    public class UsersController : Controller
    {
        [Route("Index")]
        public async Task<IActionResult> Index()
        {
            return View(await _context.Users.ToListAsync());
        }

        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var users = await _context.Users.FindAsync(id);
            if (users == null)
            {
                return NotFound();
            }
            return View(users);
        }
         }

Search Flipkart Products:
Flipkart.com

No comments: