我在控制器中有一个方法ApplicationsController
,我需要获取操作方法的基本URL:
public ActionResult MyAction(string id) { var url = Url.Action("MyAction", "Applications"); ... }
问题是这包括string id
当前路由数据,当我需要URL时(URL用于在基于URL的查找中从CMS获取内容).
我试过传递null
并new { }
作为routeValues
参数无济于事.
匹配路由如下(高于所有其他路由):
routes.MapLowercaseRoute( name: "Applications", url: "applications/{action}/{id}", defaults: new { controller = "Applications", action = "Index", id = UrlParameter.Optional });
我已经看到了其他一些问题,但它们似乎没有一个可行的解决方案.目前,我正在使用硬编码控制器中的路径; 但是,我希望能够将其抽象为动作过滤器,因此我需要能够生成URL.
是否有一种干净/传统的方法来防止这种行为?
使用null或empty值id
来防止Url.Action
使用当前值:
var url = Url.Action("MyAction", "Applications", new { id = "" })
最后以不同的方法解决这个问题.我能想出的唯一方法是阻止任意命名的路由值插入到生成的URL中,这是RouteData
在调用时临时删除它们的方法Url.Action
.我写了几个扩展方法来促进这个:
public static string NonContextualAction(this UrlHelper helper, string action) { return helper.NonContextualAction(action, helper.RequestContext.RouteData.Values["controller"].ToString()); } public static string NonContextualAction(this UrlHelper helper, string action, string controller) { var routeValues = helper.RequestContext.RouteData.Values; var routeValueKeys = routeValues.Keys.Where(o => o != "controller" && o != "action").ToList(); // Temporarily remove routevalues var oldRouteValues = new Dictionary<string, object>(); foreach (var key in routeValueKeys) { oldRouteValues[key] = routeValues[key]; routeValues.Remove(key); } // Generate URL string url = helper.Action(routeValues["Action"].ToString(), routeValues["Controller"].ToString()); // Reinsert routevalues foreach (var kvp in oldRouteValues) { routeValues.Add(kvp.Key, kvp.Value); } return url; }
这允许我在动作过滤器中执行此操作,其中我不一定知道动作的参数名称是什么(因此不能像在其他答案中那样仅传递匿名对象).
然而,仍然非常有兴趣知道某人是否有更优雅的解决方案.
好的,我看到了问题.这就是所谓的"段变量重用".生成出站URL的路由,并尝试在路由的URL模式中查找每个段变量的值时,路由系统将查看当前请求中的值.这种行为使许多程序员感到困惑,并且可能导致冗长的调试会话.路由系统热衷于对路由进行匹配,以至于它将重用来自传入URL的段变量值.所以我认为你必须覆盖Julien建议的价值:
var url = Url.Action("MyAction", "Applications", new { id = "" })