IT Cloud Contrib

Open source contributions from IT Cloud Company.

ITCloud.Web.Mvc.dll

.NET 3.5 assembly containing extensions to ASP.NET MVC version 1.0.

Further development of this library is now under the IT Cloud Web Routing project.

UrlRouteAttribute

The UrlRouteAttribute class in ITCloud.Web.Mvc 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.Mvc;

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.Mvc.RouteUtility.RegisterUrlRoutesFromAttributes from your Application_Start method in Global.asax:

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

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.
            RouteUtility.RegisterUrlRoutesFromAttributes(routes);
        }

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


Under the hood, the RegisterUrlRoutesFromAttributes 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.

Getting Started with UrlRouteAttribute

These are the steps required to use UrlRoute attributes:
  1. Download and unzip the ITCloud.Web.Mvc.dll assembly to your local development environment. You may also download the source and build the assembly yourself using Visual Studio 2008.
  2. Reference the ITCloud.Web.Mvc.dll assembly in your project.
  3. Add a using namespace ITCloud.Web.Mvc; statement to the top of each controller class file where you plan to use the UrlRoute attribute.
  4. Affix your controller action methods with the UrlRoute and related attributes as appropriate (see examples above).
  5. In your Global.asax file, instead of adding the routes manually, call the ITCloud.Web.Mvc.RouteUtility.RegisterUrlRoutes method (see example above).

Other Examples

For another UrlRoute attribute example and discussion, please visit this topic on StackOverflow.

Last edited Apr 4, 2011 at 5:38 AM by ds7, version 5