Search code examples
asp.net-mvcc#-4.0asp.net-mvc-routing

MVC Route Configuration


I have the following in my HomeController:

public ActionResult Share(string id)
{
    Debate debate;
    try
    {
        debate = Db.Debates.Single(deb => deb.ShareText.Equals(id));
    }
    catch (Exception)
    {
        return RedirectToAction("Index");
    }
    return View(debate);
}

This allows me to call the url this way:

http://localhost:50499/Home/Share/SomeTextHere

I configured the route this way in the routeconfig file:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

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

I want to be able how to call the URL this way:

http://localhost:50499/Debate/SomeTextHere

I have been struggling with this with no luck. What is the best way to achieve it?


Solution

  • As mentioned in the comments by @StephenMuecke you would need to change the route to not make it so general.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            name: "Share",
            url: "Debate/{id}",
            defaults: new { controller = "Home", action = "Share", id = UrlParameter.Optional }
        );
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
    

    the Share route would now allow http://localhost:50499/Debate/SomeTextHere to route to the appropriate controller action.