UrlRouteAttribute

The UrlRouteAttribute class in ITCloud.Web.Routing allows you to associate routes with controller actions in a more natural way than what is provided out-of-the-box by the ASP.NET MVC framework: as .NET attributes on the controller action method definitions. Instead of defining every route in Application_Start, you affix your controller action methods with the UrlRoute attribute which specifies the path and other properties of the route.

The following hypothetical Blog controller written in C# illustrates how to associate routes with controller action methods using the UrlRoute attribute along with the optional UrlRouteParameterContraint and UrlRouteParameterDefault attributes:

using System;
using System.Web.Mvc;
using ITCloud.Web.Routing;

namespace BlogEngine.Controllers
{
    public class BlogController : Controller
    {
        //
        //  UrlRoute Name property is optional, it can be used when generating
        //  outbound links (e.g. via Html.RouteLink).
        //
        //  UrlRoute Path property is required, and contains the URL that
        //  will be routed to the action method.  It must not begin with "/".
        //
        [UrlRoute(Name = "Home", Path = "")]
        public ActionResult Index()
        {
            return View();
        }

        //
        //  Route paths containing parameters (e.g. "title" below) are
        //  mapped to action method parameters of the same name.
        //
        //  Optional UrlRouteParameterDefault attribute allows you to
        //  specify a default value for a parameter if it is omitted in
        //  the incoming URL.
        //
        [UrlRoute(Path = "blogs/{title}")]
        [UrlRouteParameterDefault(Name = "title", Value = "latest-post")]
        public ActionResult BlogEntryByTitle(string title)
        {
            // omitted code to retrieve blog based on title

            return View();
        }

        //
        //  The UrlRouteParameterContraint attribute specified below
        //  ensures that an incoming URL routes to this method only if
        //  the postDate parameter matches the date format YYYY-MM-DD
        //  (using the RegEx).  E.g. blogs/2009-07-15
        //
        //  The UrlRoute Order property specifies the order in which the
        //  route is evaluated relative to other routes.  The default Order
        //  value if not specified is 0.  If multiple routes have the same
        //  Order, then the order in which they are evaluated relative to
        //  each other is undefined and should not be relied upon.
        //
        //  In the route below, it is necessary to specify a negative Order
        //  value to ensure that the route is evaluated before the
        //  BlogEntryByTitle route specified above.  Otherwise, even if the
        //  incoming URL contains a postDate in YYYY-MM-DD format, the other
        //  route could potentially be evaluated first, which would match
        //  but would not be the desired outcome in this case.
        //
        [UrlRoute(Path = "blogs/{postDate}", Order = -10)]
        [UrlRouteParameterConstraint(Name = "postDate", Regex = @"^\d\d\d\d-\d\d-\d\d$")]
        public ActionResult BlogEntriesByDate(DateTime postDate)
        {
            // omitted code to retrieve blogs that were posted on postDate

            return View();
        }
    }
}


Once you have affixed your controller action methods with the appropriate UrlRoute attributes, you can add the routes automatically by calling ITCloud.Web.Routing.RouteExtensions.DiscoverMvcControllerRoutes from your Application_Start method in Global.asax:

using System.Web.Mvc;
using System.Web.Routing;
using ITCloud.Web.Routing;

namespace BlogEngine
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            // No longer need this default route.
            //routes.MapRoute(
            //    "Default",                                              // Route name
            //    "{controller}/{action}/{id}",                           // URL with parameters
            //    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            //);

            // Add routes for UrlRoute attributes defined on Controller action methods.
            routes.DiscoverMvcControllerRoutes();
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}


Under the hood, the DiscoverMvcControllerRoutes function uses reflection to enumerate all the controllers in the calling method's assembly, and creates routes for any UrlRoute attributes associated with the controller action methods. Routes are created via calls to the RouteCollectionExtensions.MapRoute method which is part of ASP.NET MVC.

Last edited Apr 4, 2011 at 6:17 AM by ds7, version 1

Comments

No comments yet.