Question

Suppose I want to publish (like in paper catalogs) some "short URLs" that are easy to type/remember, but I want them to redirect to a verbose, SEO-friendly URL. How do I accomplish that with MVC routes?

Example:

http://mysite.com/disney

becomes

http://mysite.com/travel/planning-your-disney-vacation (with "travel" as the Controller)

The things I've tried:

  1. Just setup a route for it. Problem: the URL doesn't change in the browser (it stays "/disney".

  2. Use NuGet package RouteMagic (see Haacked's article). Problem: I get an error: The RouteData must contain an item named 'controller' with a non-empty string value. I think this is because I don't have a static word before my controller ("travel") like he did (with "foo" and "bar")???

  3. Use a redirect module (like Ian Mercer's). Problem: the route matches on my HTML.ActionLinks when creating URLs which I don't want (Haacked mentions this in his article and says that's why he has GetVirtualPath return NULL ...?)

I'm out of ideas, so any would be appreciated! Thanks!

Was it helpful?

Solution

You could set up a catch-all type route, to direct all /something requests to a specific action and controller, something like:

routes.MapRoute(
    "ShortUrls",
    "{name}",
    new {controller = "ShortUrl", action = "Index", name = UrlParameter.Optional}
);

(depending on how the rest of your routing is set up, you probably don't want to do it exactly like this as it will likely cause you some serious routing headaches - but this works here for the sake of simplicity)

Then just have your action redirect to the desired URL, based on the specified value:

public class ShortUrlController : Controller
{
    //
    // GET: /ShortUrl/

    public ActionResult Index(string name)
    {
        var urls = new Dictionary<string, string>();
        urls.Add("disney", "http://mysite.com/travel/planning-your-disney-vacation");
        urls.Add("scuba", "http://mysite.com/travel/planning-your-scuba-vacation");

        return Redirect(urls[name]);
    }
}

OTHER TIPS

I just faced the same problem. In my Global:

routes.MapRoute(
    "ShortUrls",
    "{name}",
    new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);

In my Home Controller:

public ActionResult Index(string name)
{
    return View(name);
}

This way is dynamic, didn't want to have to recompile every time I needed to add a new page.

To shorten a URL you should use URL rewriting technique.

Some tutorials on subject:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top