Alex
Alex

Reputation: 38529

Getting url path from ASP.net MVC route

I have a controller that looks like this:

public class PageController : Controller
{
    public ActionResult Render(string url)
    {
        //this is just for testing!
        return Content("url was " + url);
    }
}

I'm trying to pass in the value of the url into the controller. For example:
http://www.site.com/products/something/else

Would pass "products/something/else" into my Render action of the PageController.

This is because we are using "products/something/else" as a unique key for a record in the database (legacy system, don't ask)

So, my resultant query would be something along the lines of this:

select * from foo where urlKey = 'products/something/else'

So far I have this in my RegisterRoutes section on Global.asax:

routes.MapRoute("pages", "{*url}", new { controller = "Page", action = "Render", url="/" });

But this isn't working as expected...

By visiting www.site.com/products/something/else, the value passed into the controller is "home/index/0"
The only route defined in RegisterRoutes is that described in the question.

Upvotes: 0

Views: 2779

Answers (2)

VJAI
VJAI

Reputation: 32768

The below class matches every route but you can modify as per your needs.

public class LegacyRoute : RouteBase
{
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
      RouteData result = null;

      string url = httpContext.Request.RawUrl.Substring(1);

      result = new RouteData(this, new MvcRouteHandler());
      result.Values.Add("controller", "Page");
      result.Values.Add("action", "Render");
      result.Values.Add("url", url);

      return result;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
      return null;
    }
}

In Global.asax.cs

routes.Add(new LegacyRoute());

Upvotes: 3

Gaz Winter
Gaz Winter

Reputation: 2989

Hope this helps, one of our routes does something similar and this is the code:

   routes.MapRoute(
            name: "Standard",
            url: "{controller}/{action}/{id}",
            defaults: new { id = UrlParameter.Optional, action = ControllersAndActions.TypicalController.IndexAction, page = 1 },
            constraints: new
            {
                controller = ControllersAndActions.ControllerConstraintExpression
            }
        );

Upvotes: 0

Related Questions