web analytics

Enabling Attribute Routing in ASP.NET MVC

Options

codeling 1602 - 6666
@2022-08-09 14:21:39

When a MVC application starts the first time, the Application_Start() event of global.asax is called. This event registers all routes in the route table using the RouteCollection.MapRoute method.

//global.asax.cs

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
 

//RouteConfig.cs

public class RouteConfig  

{  

    public static void RegisterRoutes(RouteCollection routes)  

    {  

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  

        routes.MapRoute(  

               "Default", // Route name  

                "{controller}/{action}/{id}", // URL with parameters  

                new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  

           );  

    }  

Attribute Routing

Attribute Routing enables us to define routing on top of the controller action method using route attributre. To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration.

//RouteConfig.cs

public class RouteConfig  

{  

    public static void RegisterRoutes(RouteCollection routes)  

    {  

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  

        routes.MapMvcAttributeRoutes();  

        routes.MapRoute(  

               "Default", // Route name  

                "{controller}/{action}/{id}", // URL with parameters  

                new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  

           );  

    }  

The following is the example of a Route Attribute in which routing is defined where the action method is defined.

public class HomeController : Controller  

{  

    //URL: /Mvctest  

    [Route(“Mvctest”)]  

    public ActionResult Index()  

        ViewBag.Message = "Welcome to ASP.NET MVC!";  

        return View();  

}}   

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com