我有一个看起来像这样的控制器:
public class PageController : Controller
{
public ActionResult Render(string url)
{
//this is just for testing!
return Content("url was " + url);
}
}
我正在尝试将url的值传入控制器。例如:
http://www.site.com/products/something/else
将“products / something / else”传递给PageController的Render操作。
这是因为我们使用“products / something / else”作为数据库中记录的唯一键(遗留系统,不要问)
所以,我的结果查询将是这样的:
select * from foo where urlKey = 'products/something/else'
到目前为止,我在Global.asax的RegisterRoutes部分中有这个:
routes.MapRoute("pages", "{*url}", new { controller = "Page", action = "Render", url="/" });
但这不符合预期......
访问www.site.com/products/something/else,传入控制器的值为“home / index / 0”
RegisterRoutes中定义的唯一路径是问题中描述的路径。
答案 0 :(得分:3)
以下课程与每条路线相匹配,但您可以根据自己的需要进行修改。
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;
}
}
在Global.asax.cs
中routes.Add(new LegacyRoute());
答案 1 :(得分:0)
希望这会有所帮助,我们的其中一条路线做了类似的事情,这就是代码:
routes.MapRoute(
name: "Standard",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional, action = ControllersAndActions.TypicalController.IndexAction, page = 1 },
constraints: new
{
controller = ControllersAndActions.ControllerConstraintExpression
}
);