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

标签 c# blazor .net-5

在我的应用程序中,我有一个用户可以提交的表单。当他们提交表单时,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 数组添加新值使用相同的 key 。

最佳答案

您的字典已有一个带有键 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"});

关于c# - 如何使用相同的键向 StringValues 数组添加新值,从而修改我的 Uri?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68897824/

相关文章:

c# Dictionary<DateTime, List<Item>> 按日期时间排序列表(可为空值)

c# - Xamarin Studio 中的断点未命中

c# - 选择选项下拉列表不显示所选选项

c# - 复杂的正则表达式问题

c# - 无法加载文件或程序集 CrystalDecisions.ReportAppServer.ClientDoc

onchange - blazor editform 更改事件

dll - 在浏览器中运行 C# dll 仅用于计算

asp.net-core - Visual Studio 2019 Net 5 ASP.NET Core Web应用程序错误MSB3644找不到.NETFramework的引用程序集,版本=v5.0

c# - .NET5 JsonPatchDocument.ApplyTo 在添加或替换时抛出

azure - 使用 postman 进行测试,即使 Azure AD 身份验证正常,也会出现错误 401 未经授权