将 QueryString 附加到 asp.net 核心锚助手标签中的 href

Append QueryString to href in asp.net core Anchor Helper Tag

我正在尝试在 html 结果的锚点请求查询中添加任何内容:

虚构的例子:

用户发出请求(请注意,乐队和歌曲可以是任何东西,我有一个满足此请求的路线:模板:“{band}/{song}”):

http://mydomain/band/song?Param1=111&Param2=222

现在我希望我的锚点将查询字符串部分附加到我的锚点的 href。所以我尝试了这样的事情(注意 'asp-all-route-data'):

<a asp-controller="topic" asp-action="topic" asp-route-band="iron-maiden" asp-route-song="run-to-the-hills" asp-all-route-data="@Context.Request.Query.ToDictionary(d=>d.Key,d=>d.Value.ToString())">Iron Maiden - Run to the hills</a>

查询字符串的追加实际上适用于上述代码,但结果中丢失了 "iron-maiden" 和 "run-to-the-hills"。上面的标签助手 returns 以下(注意助手如何将请求中的乐队和歌曲镜像到 href 而不是我在 asp-route 属性中指定的乐队和歌曲):

<a href="http://mydomain/band/song?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>

我希望助手能得到以下结果:

<a href="http://mydomain/iron-maiden/run-to-the-hills?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>

似乎当我使用 asp-all-route-data 时我松开了 asp-route-band asp-route-song 结果中的值。

有没有人偶然发现这个?

谢谢

呼呼

似乎还没有任何官方方法可以做到这一点。

如果 @Context.GetRouteData().Values 有效,您应该改用它。其背后的想法是,GetRouteData 从路由中间件获取当前路由信息作为键值对(字典),其中还应包含查询参数。

我不确定它是否适用于您的情况,以及 asp-route-bandasp-route-song 是硬编码的还是从您的情况中获取的。

万一不行,您可以试试下面的扩展方法 & class:

public static class QueryParamsExtensions
{
    public static QueryParameters GetQueryParameters(this HttpContext context)
    {
        var dictionary = context.Request.Query.ToDictionary(d => d.Key, d => d.Value.ToString());
        return new QueryParameters(dictionary);
    }
}

public class QueryParameters : Dictionary<string, string>
{
    public QueryParameters() : base() { }
    public QueryParameters(int capacity) : base(capacity) { }
    public QueryParameters(IDictionary<string, string> dictionary) : base(dictionary) { }

    public QueryParameters WithRoute(string routeParam, string routeValue)
    {
        this[routeParam] = routeValue;

        return this;
    }
}

它基本上从上面的扩展方法后面抽象出你的代码,return是一个 QueryParameters 类型(这是一个扩展的 Dictionary<string,string>),为了纯粹方便,还有一个额外的方法,所以您可以链接多个 .WithRoute 调用,因为字典的 Add 方法具有 void return 类型。

你会像这样从你的视图中调用它

<a  asp-controller="topic"
    asp-action="topic" 
    asp-all-route-data="@Context.GetQueryParameters().WithRoute("band", "iron-maiden").WithRoute("song", "run-to-the-hills");"
>
    Iron Maiden - Run to the hills
</a>