Question

I am writing an MVC 4 application which has controllers and many lengthy action names, and they create a lengthy URL which is not easy to remember.

Any idea of how we can implement short URLs (Preferably, without affecting routing) in MVC 4? May be using custom attributes?

Was it helpful?

Solution

Actually, you can specify your routes in RouteConfig.cs. Here is the code from my application:

    routes.MapRoute("SignUp", "signup", new { controller = "SignUp", action = "Index" });
    routes.MapRoute("SignOut", "signout", new { controller = "Login", action = "SignOut" });
    routes.MapRoute("Login", "login", new { controller = "Login", action = "Login" });

Second parameter here (signup, signout, login) are the short urls. If you want something more, you can specify your routes like this:

    routes.MapRoute("SetNewPassword", "set-new-password/{userId}/{passwordResetKey}", new { controller = "SetNewPassword", action = "Index" });

The url here is something like /set-new-password/123/blabla

New routes don't affect default routes. Just make sure you have this default line at the end:

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

Btw, you can use handy route debugger from Phil Haack. It's really easy to set up and use (you just need to comment/uncomment one single line in your Global.asax.cs). It's absolutely must have tool for every Asp.Net MVC developer.

OTHER TIPS

May be a "catchall" routing will help you.

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://..your lengthy url");
    urls.Add("scuba", "http://another..lengthy url");
    return Redirect(urls[name]);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top