views:

489

answers:

1

I'm attempting to write a TinyURL like clone in ASP.NET MVC as a first project to get used to the framework.

The URL routing is still a little confusing for me, especially when I deviate from the controller/action/id.

Can any of you ASP.NET MVC ninjas help me setup a simple URL route similar to how TinyURL.com processes its routes?

For example:

www.tinyurl.com/

Redirects to the index page. So, if no parameters are passed, then simply call the Index() view.

However, if you pass in your tinyurl hash, I need call the redirect() action.

www.tinyurl.com/fbc13

So, how would I go about setting up this custom route?

 routes.MapRoute(  
                "Default",                              // Route name  
                "{tinyhash}",                           // URL with parameters  
                new { controller = "Link", action = "ReDirect", tinyhash = "" }  // Parameter defaults  
            );

This isn't quite right, because if you just visit the page with no hash in the url, I've got it defaulting to the ReDirect() action when I want it to instead, call the Index() method.

Suggestions for how to mimic a basic TinyURL like route?

+10  A: 

You are on the right track. Create an empty route and you'll not be redirected.

routes.MapRoute(  
    "Default",
    "",
    new { controller = "Home", action = "Index" }
);

and change your default one to

routes.MapRoute(  
    "Redirect",
    "{tinyhash}", 
    new { controller = "Link", action = "ReDirect", tinyhash = "" } 
);

Alternatively you could just have the controller check the tinyhash value and show a different view if it is empty. (that is hacky)

Brendan Enrick
@benrick, thanks a ton!
KingNestor