C#中如何将自定义请求头字典转换为字符串输出
问题原因
Dictionary<TKey,TValue> 没有重写基类 Object 的 ToString() 方法,默认实现只会返回对象的完整类型名称,不会输出内部存储的键值对内容,这就是你得到System.Collections.Generic.Dictionary2[System.String,System.String]输出的原因。 另外你现有代码还有一个错误:File.WriteAllText`方法的第一个参数是目标文件的完整路径,第二个参数是要写入的文本内容,你原代码的两个参数顺序颠倒,会导致写入逻辑不符合预期。
修复方案
适配现有代码的完整实现
StringBuilder sb = new StringBuilder(); sb.Append(Environment.NewLine); sb.AppendLine("Context headers passed in the request"); Dictionary<string, string> customHeaders = new Dictionary<string, string>(); customHeaders.Add("If-Match", passedEtag); customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a"); // 遍历字典拼接所有键值对 foreach (var headerItem in customHeaders) { sb.AppendLine($"{headerItem.Key}: {headerItem.Value}"); } // 拼接完整输出路径,写入文件 string fullOutputPath = Path.Combine(@"C:\Testing", "headersoutput.txt"); File.WriteAllText(fullOutputPath, sb.ToString());
简化写法(可选)
如果你不需要复杂的格式控制,可以用LINQ一行完成键值对拼接:
string headerContent = string.Join(Environment.NewLine, customHeaders.Select(kv => $"{kv.Key}: {kv.Value}"));
执行后输出的文件内容就会符合预期:
Context headers passed in the request If-Match: [你的passedEtag变量实际值] context_study_site: edc42643-27b5-428e-b8ae-2fa19bfb457a
内容的提问来源于stack exchange,提问作者RShome
相关产品推荐
相关产品推荐

