如何向同Key的StringValues数组添加新值以修改Uri?
问题原因
Dictionary<string, StringValues>的Add方法要求键全局唯一,当你已经添加过include键后,再次调用Add传入相同的键就会触发重复键异常。你需要的是给已存在的键对应的StringValues追加新值,而非新增重复键。
解决方案
StringValues本身就支持存储多个字符串值,你只需要在添加前先判断键是否存在,存在就合并新旧值,不存在再新增键即可。
单次追加单个值的代码
string newInclude = "option:mudguards"; if (choices.ContainsKey("include")) { // 合并已有值和新值 choices["include"] = StringValues.Concat(choices["include"], new StringValues(newInclude)); } else { choices.Add("include", new StringValues(newInclude)); }
批量追加多个值的代码
如果要一次性添加多个include值,可以直接遍历批量处理:
// 预定义所有需要添加的include参数值 var addIncludeList = new List<string> { "option:siriusxm", "option:mudguards", "color:blue" }; foreach (var val in addIncludeList) { if (choices.TryGetValue("include", out var existingVals)) { choices["include"] = StringValues.Concat(existingVals, val); } else { choices.Add("include", val); } }
执行完上述代码后,choices里的include键就会对应你期望的三个值,和原有的q、exclude参数格式完全一致。
额外优化提示
你原有代码中不需要手动调用System.Net.WebUtility.UrlDecode处理URI,navigationManager.ToAbsoluteUri和QueryHelpers.ParseQuery会自动处理编码逻辑,多余的解码操作可能在参数包含特殊字符时引发异常,可以简化为:
Uri uri = navigationManager.ToAbsoluteUri(navigationManager.Uri); Dictionary<string, StringValues> choices = QueryHelpers.ParseQuery(uri.Query);
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

