ASP.NET MVC > Route

Expose action method by certain URL (attribute routing) in ASP.NET MVC

How to expose an action method by a certain url (attribute routing)?


In order to expose a controller action method by a certain url, we can use attribute routing ie. specifying the route with the help of attribute on action methods. To achieve this we need to modify our App_Start/RouteConfig.cs file a bit.

APP_START/ROUTECONFIG.CS CODE

 public static void RegisterRoutes(RouteCollection routes)
        {
            
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            
            // important to work with AttributeRouting
            routes.MapMvcAttributeRoutes();

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

Notice the highlighted code above. This is important to work with the attribute routing. If this method is not called in the RouteConfig.cs, attribute routing doesn’t work.

Now here is the action method of the controller that we want to expose with a specific url

CONTROLLER CODE

[Route("ITFunda")]
public ActionResult AttributeRouting()
{
    return View("/Views/RoutingStuffs/ITFunda.cshtml");
}

Notice the attribute defined on the AttributeRouting() action method above. In this case, we are instructing the ASP.NET MVC Framework that if a request comes with url http://servername/ITFunda; route it to this action method irrespective of in which controller it is defined.

VIEW CODE

@{
    ViewBag.Title = "ITFunda";
}

<h2>ITFunda</h2>

<img src="~/Images/itfunda.gif" />

This view simply shows the itfunda image.

How it works?

When we request the url http://localhost:63087/itfunda or http://localhost:63087/ITFunda , because of MapMVCAttributeRoutes() method call in the RouteConfig.cs (it enables the attribute routing), the ASP.NET MVC framework searches for "ITFunda" in any Route attributes in the action methods apart from the default route specified in this file and if this particular string is found on any specific action method with Route attribute, that action method is executed.

Requesting the above url, gives us below output in the browser as the action method returns ITFunda.cshtml view that simply displays the itfunda image.

POINT OF INTEREST

Apart from just specifying static string in the Route attribute of Action method, we can also specify segments variables. To learn more about it, please visit http://www.dotnetfunda.com/articles/show/3030/attributerouting-in-aspnet-mvc-5 article. 

 Views: 10277 | Post Order: 71



Write for us






Hosting Recommendations