UrlHelper.Action包含不需要的附加参数

时间:2013-12-03 11:18:13

标签: c# asp.net-mvc-4 urlhelper

我在控制器ApplicationsController中有一个方法,我需要在其中获取操作方法的基本URL:

public ActionResult MyAction(string id)
{
    var url = Url.Action("MyAction", "Applications");
    ...
}

问题是这包括当前路由数据中的string id,当我不需要URL时(URL用于在基于URL的查找中从CMS获取内容)。

我尝试将nullnew { }作为routeValues参数传递无效。

匹配路线如下(高于所有其他路线):

routes.MapLowercaseRoute(
    name: "Applications",
    url: "applications/{action}/{id}",
    defaults: new { controller = "Applications",
                    action = "Index", id = UrlParameter.Optional });

我已经看到了其他一些问题,但似乎没有一个问题可行。目前,我正在使用硬编码控制器中的路径;但是,我希望能够将其抽象为动作过滤器,因此我需要能够生成URL。

是否有一种干净/传统的方法可以防止这种行为?

4 个答案:

答案 0 :(得分:12)

好的,我看到了问题。它被称为"段变量重用"。生成出站URL的路由,并尝试在路由的URL模式中查找每个段变量的值时,路由系统将查看当前请求中的值。这种行为使许多程序员感到困惑,并且可能导致冗长的调试会话。路由系统热衷于对路由进行匹配,以至于它将重用来自传入URL的段变量值。所以我认为你必须像Julien建议的那样覆盖价值:

var url = Url.Action("MyAction", "Applications", new { id = "" })

答案 1 :(得分:7)

通过不同的方法结束了解决这个问题。我可以提出的唯一方法是阻止任意命名的路由值插入生成的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;
}

这允许我在动作过滤器中执行此操作,我不一定知道动作的参数名称是什么(因此不能像其他答案那样只传递匿名对象)。

然而,仍然非常有兴趣知道某人是否有更优雅的解决方案。

答案 2 :(得分:6)

使用id的空值或空值来阻止Url.Action使用当前值:

var url = Url.Action("MyAction", "Applications", new { id = "" })

答案 3 :(得分:0)

我对@AntP本来很好的解决方案中RouterData的更改,瞬态或其他方式并不完全满意。由于创建链接的代码已经集中,因此我借用了@TomaszJaskuλa和@AntP来扩展ExpandoObject

IDictionary<string,object> p = new ExpandoObject();

// Add the values I want in the route
foreach (var (key, value) in linkAttribute.ParamMap)
{
    var v = GetPropertyValue(origin, value);                    
    p.Add(key, v); 
}

// Ideas borrowed from https://stackoverflow.com/questions/20349681/urlhelper-action-includes-undesired-additional-parameters
// Null out values that I don't want, but are already in the RouteData
foreach (var key in _urlHelper.ActionContext.RouteData.Values.Keys)
{
    if (p.ContainsKey(key))
        continue;

    p.Add(key, null); 
}

var href = _urlHelper.Action("Get", linkAttribute.HRefControllerName, p);