Shaul Behr
Shaul Behr

Reputation: 38003

ASP.NET MVC: how to make all unspecified URLs direct to one controller

I've got an ASP.NET MVC app that's working nicely with a handful of controllers, e.g. "Home", "Services" and "Go". The "Go" controller is where all the content is.

Now the marketing folks have come and said they don't want to see the word "go" in the URL. In other words, instead of:

http://mydomain.com/go/geography/africa

they want to have:

http://mydomain.com/geography/africa

I cannot create a controller for every path that they might want... so is there any way of writing my routing in Global.asax.cs in such a way that requests to "services" and "home" will be treated the normal way, but anything else will implicitly be routed to the "go" controller?

Upvotes: 1

Views: 334

Answers (5)

Ian Oxley
Ian Oxley

Reputation: 11056

Are you on IIS7? It might be easiest to just implement URL rewriting on the server for this, rather than hacking about with your routes in Global.asax.cs.

EDIT: I've only ever done URL rewriting in Apache. For what it's worth that would be done using something like this:

RewriteEngine On
RewriteRule ^go/(.+)$ /$1 [R=301,L]

Have a look at http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/ and http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/. Hopefully they'll give you enough info to be able to get this working in IIS 7

Upvotes: 3

Shaul Behr
Shaul Behr

Reputation: 38003

Hey, I worked it out myself, without URL rewriting!

Inside RegisterRoutes() in Global.asax.cs:

routes.MapRoute("Services", "services/{action}/{*qualifier}",
  new { controller = "Services", action = "Index", qualifier = UrlParameter.Optional });
// and other controllers that I want to work the normal way
routes.MapRoute("Default", "{*path}", 
  new { controller = "Go", action = "Index", path = UrlParameter.Optional });

And in my GoController class

public ActionResult Index(string path) { ... }

Works perfectly!

Upvotes: 2

Joshua
Joshua

Reputation: 8212

You could try adding a mapping that does "geography/{country}" and have it specify the controller manually and add the country as a parameter. I've seen it done to prevent things like "Dashboard/Dashboard" etc.

An example can be seen at Kazi Manzur Rashid's Blog - ASP.NET MVC Best Practices (Part 2) #15 for what I am describing.

Upvotes: 1

Massif
Massif

Reputation: 4433

you could try mapping a route of "{action}/{id}" with a default set for the controller. But that'll also match anything of the form "{controller}/{action}" too - unless you can do some clever constraining.

Upvotes: 0

Related Questions