What Is Attribute based Routing?

What Is Attribute based Routing?

What Is Attribute based Routing?
MVC 5 supports a new type of routing that called attribute routing. It used to define routes.

Enable Attribute Routing - If you want to use Attribute Routing, you must enable it by calling MapMvcAttributeRoutes on the RouteCollection.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
        //Enables Attribute Routing
        routes.MapMvcAttributeRoutes();
    }
}

Defining a Route - A route attribute has to be defined on top of an action method or on the top of a controller.

The Example looks like,
public class HomeController: BaseController
{
  [Route("User/GetUsers")]
  public ActionResult GetUsers(int Id)
  {
      return View();
  }
}

Custom Routes -
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "User",
            url: "User/{id}",
            defaults: new { controller = "User", action = "Index"}
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

What Is Attribute based Routing? What Is Attribute based Routing? Reviewed by Anil Singh on 3:09 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^