如何使用相同的键向 StringValues 数组添加新值,从而修改我的 Uri?

How can I add a new value to a StringValues array, with the same key, thereby modifying my Uri?

在我的应用程序中,我有一个用户可以提交的表单。当他们提交表单时,URL 看起来像这样:

https://localhost:5003/searchresults/q=ford&q=bronco&exclude=color:red&exclude=interior:cloth

OnInitializedAsync 中的 SearchResults.razor 我有这段代码:

String url = System.Net.WebUtility.UrlDecode(navigationManager.Uri);
Uri uri = navigationManager.ToAbsoluteUri(url);
Dictionary<string, StringValues> choices = QueryHelpers.ParseQuery(uri.Query);

在调试器中,我看到“选择”是这样的:

{[q, {ford,bronco}]}
{[exclude, {color:red,interior:cloth}]}

在下一页说我要添加:

&include=option:siriusxm
&include=option:mudguards
&include=color:blue

要使“选择”看起来像这样:

{[q, {ford,bronco}]}
{[exclude, {color:red,interior:cloth}]}
{[include, {option:siriusxm,option:mudguards,color:blue}]}

如果我这样做:

StringValues sv = new StringValues("option:siriusxm");
choices.Add("include", sv);

这会奏效。但是,如果我继续并执行此操作:

StringValues sv = new StringValues("option:mudguards");
choices.Add("include", sv);

我会得到错误:

ArgumentException: An item with the same key has already been added. Key: include
System.Collections.Generic.Dictionary<TKey, TValue>.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
System.Collections.Generic.Dictionary<TKey, TValue>.Add(TKey key, TValue value)
MyAwesomeApplication.Pages.SearchResults.OnInitializedAsync() in SearchResults.razor
+
    choices.Add("include", sv);

我是 C#、ASP.NET 和 Blazor 的新手,所以我不确定如何添加 只是 一个新值到现有的 StringValues 具有相同键的数组。

您的字典中已经有一个关键字为 include 的项目,您必须将新值附加到现有的 StringValues:

StringValues sv = new StringValues("option:siriusxm");
sv = StringValues.Concat(sv,"option:mudguards");

StringValues sv = new StringValues("option:siriusxm");
choices.Add("include", sv);
choices["include"] = StringValues.Concat(choices["include"],"option:mudguards");

甚至更好:

StringValues sv = new StringValues(new string[]{"option:siriusxm","option:mudguards"});