I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?
You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)
01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }
You implement a controller named HomeController that includes methods with the following
signatures.
public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)
You need to add a route to meet the following requirements:
-
The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.
-
User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?
A. Replace line 05 with the following code segment.
routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );
B. Replace line 05 with the following code segment.
routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );
C. At line 04, add the following code segment.
routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );
D. At line 04, add the following code segment.
routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );
When an ASP.NET MVC route looks for an action to map to, it takes several things into account:
Because of that, if you want a route that matches the criteria you listed, this route would be the correct answer:
A URL with this structure would match that route for the following reasons:
C is the correct answer as it adds to the current routes.
Answer B replaces the existing route definition, thus preventing the default routing to the
HomecontrollerIndexaction.