简体   繁体   中英

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.

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());

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
            }
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM