Search code examples
asp.netasp.net-mvc-3asp.net-mvc-routingcustom-routes

ASP.NET MVC3 dynamic routing


I'm having trouble finding the answer to this question anywhere.

I am in need of creating a form where the user can create a post and change the url to the post.

For example, if the default route is

http://www.domain.com/posts/[the-title-of-the-post]

The user can change this to

http://www.domain.com/[modified-title-of-the-post].

The [modified-title-of-the-post] can be anything the user would like to make it. This means it is no longer tied to the title of the post and not only that, but the /posts/ is gone too.

I guess I should Also mention that this should be global, meaning the user should be able to change the url (as mentioned above) for other things on the sites like, /topics/ or /blog/

Any help would be greatly appreciated,

Thanks, Hiva


Solution

  • You could create two routes in your global.asax. Something like this

    routes.MapRoute("", "posts/{url}", new { controller = "Home", action = "Posts" });
    routes.MapRoute("", "{url}", new { controller = "Home", action = "Posts" });
    

    both of them point to HomeController and the action Posts

    public ActionResult Posts(string url)
    {
    
    }
    

    to handle every url you should consider to extend the RouteBase class

    Something like that should do

    public class CustomRouting : RouteBase
    {
      public override RouteData GetRouteData(HttpContextBase httpContext)
      {
        RouteData result = null;
        string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath;
    
        //Handle the request
        //Compile the RouteData with your data
        result = new RouteData(this, new MvcRouteHandler());
        result.Values.Add("controller", "MyController");
        result.Values.Add("action", "MyAction");
        result.Values.Add("id", MyId);
        }
      }
      return result;
    }
    
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
      //I only need to handle outbound so here is ok
      return null;
    }
    

    }

    The in your global.asax you register your custom route handler

    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
      routes.Add(new CustomRouting());
    
      routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }