Can someone please explain what the following function does. I am learning Asp.net MVC and unable to understand which controller is called when and renders which view.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//register custom routes (plugins, etc)
var routePublisher = EngineContext.Current.Resolve<IRoutePublisher>();
routePublisher.RegisterRoutes(routes);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "Nop.Web.Controllers" }
);
}
This code is from nopCommerce source-code. I can’t understand the URL routing for this project
The logic for this is in the
System.Web.Mvc.MvcHandlerclass, theSystem.Web.Mvc.DefaultControllerFactoryclass, and theSystem.Web.Mvc.ControllerActionInvokerclass. .NET Reflector is your friend.Basically, the MVC framework:
Uses reflection to get all the controllers in the application project.
Then it does something like
IEnumerable<string> controllerNames = controllerTypes.Select(controllerType => controllerType.Name.Replace("Controller",string.Empty));. It then tries to match the first path segment,{controller}, to one of these sanitized controller type names (case-insensitive).Then, it looks at this controller’s public methods that have a return type that is of type
ActionResultor some derivative. It matches the method name to the second path segment,{action}, as the action method to be called.If the selected method has a parameter that is named
id, then it matches the third path segment{id}to that value, and passes it to the method. Otherwise, the optionalidparameter is ignored.If the
ActionResulttype that is returned is a derivative ofViewResultBasethen theIViewEnginetries to locate a corresponding view in the project using whatever conventions have been specified for that view engine. TheWebFormViewEngine, for example, looks in the project for~/Views/{controller}/{action}.ascx,~/Views/{controller}/{action}.aspx,~/Views/Shared/{action}.ascx,~/Views/Shared/{action}.aspxby default.If you want to further understand how routing works in MVC, I would highly suggest Scott Gu’s article on MVC Routing.
As far as the
IRoutePublishermethod, that looks like anopCommercespecific method that automatically registers additional routes specific tonopCommerce‘s configuration. If you are interested in how nopCommerce’s specific routing conventions work, you can download the source code from the nopCommerce codeplex page and do a search for its defaultIRoutePublisherimplementation.IRoutePublisheris here: http://nopcommerce.codeplex.com/SourceControl/changeset/view/7e34dd9d98f3#src%2fPresentation%2fNop.Web.Framework%2fMvc%2fRoutes%2fRoutePublisher.cs . Basically, it gets all implementations ofIRouteProviderand registers their route definitions in order according to their priority.