29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

{controller}/{action}/{id}/{*catchall}",<br />

new { controller = "Home", action = "Index",<br />

id = UrlParameter.Optional<br />

} , new[] { "URLsAndRoutes.AdditionalControllers" });<br />

}<br />

}<br />

}<br />

I express the namespaces as an array of strings and in the listing I have told the MVC Framework to look in the<br />

URLsAndRoutes.AdditionalControllers namespace before looking anywhere else.<br />

If a suitable controller cannot be found in that namespace, then the MVC Framework will default to its regular behavior and look<br />

in all of the available namespaces. If you start the app once you have made this addition to the route, you will see the result shown<br />

in Figure 15-12, which shows that the request for the root URL, which is translated in to a request for the Index action method<br />

in the Home controller, has been sent to the controller in the AdditionalControllers namespace.<br />

Figure 15-12. Giving priority to controllers in a specified namespaces<br />

The namespaces added to a route are given equal priority. The MVC Framework does not check the first namespace before<br />

moving on to the second and so forth. For example, suppose that I added both of the project namespaces to the route, like this:<br />

...<br />

routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",<br />

new { controller = "Home", action = "Index", id =<br />

UrlParameter.Optional },<br />

new[] { "URLsAndRoutes.AdditionalControllers",<br />

"UrlsAndRoutes.Controllers" });<br />

...<br />

I would see the same error as shown in Figure 15-11, because the MVC Framework is trying to resolve the controller class<br />

name in all of the namespaces added to the route. If I want to give preference to a single controller in one namespace, but have all<br />

other controllers resolved in another namespace, I need to create multiple routes, as shown in Listing 15-26.<br />

Listing 15-26. Using Multiple Routes to Control Namespace Resolution in the RouteConfig.cs File<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Linq;<br />

using System.Web;<br />

using System.Web.Mvc;<br />

using System.Web.Routing;<br />

namespace UrlsAndRoutes {<br />

public class RouteConfig {<br />

public static void RegisterRoutes(RouteCollection routes) {<br />

385<br />

routes.MapRoute("AddContollerRoute",

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!