C#构建批量API请求时如何设置Cache-Control请求头
解决C#中匿名类型无法定义带连字符键的问题
针对你遇到的匿名类型无法定义Cache-Control这类带连字符键的问题,以下是几种可行的解决方案:
方法1:用Dictionary<string, string>替代匿名类型
直接将Headers部分替换为字典,字典的键不受C#标识符规则限制,序列化后会直接生成目标JSON格式:
var batchRequest = new { GetEvents = new { Method = "GET", Headers = new Dictionary<string, string> { { "Cache-Control", "no-cache" } }, Resource = "https://xxxx" }, GetAttributes = new { Method = "GET", ParentIDs = new JArray("GetEvents"), RequestTemplate = new { Resource = "{0}?selectedFields=Items.Name;Items.Value.Value" }, Parameters = new JArray("$.GetEvents.Content.Items[*].Links.Value") } };
方法2:定义具名类并使用JsonProperty特性(基于Newtonsoft.Json)
如果需要结构化的类型定义,可创建对应类并通过JsonProperty指定JSON输出的键名,兼顾C#命名规范和JSON格式需求:
public class BatchRequestItem { public string Method { get; set; } public string Resource { get; set; } public RequestHeaders Headers { get; set; } } public class RequestHeaders { [JsonProperty("Cache-Control")] public string CacheControl { get; set; } } // 构建请求体 var batchRequest = new { GetEvents = new BatchRequestItem { Method = "GET", Resource = "https://xxxx", Headers = new RequestHeaders { CacheControl = "no-cache" } }, GetAttributes = new { Method = "GET", ParentIDs = new JArray("GetEvents"), RequestTemplate = new { Resource = "{0}?selectedFields=Items.Name;Items.Value.Value" }, Parameters = new JArray("$.GetEvents.Content.Items[*].Links.Value") } };
方法3:使用ExpandoObject动态类型
若需要灵活构建不规则结构的JSON,可借助动态类型ExpandoObject添加任意键名的属性:
dynamic getEvents = new ExpandoObject(); getEvents.Method = "GET"; getEvents.Resource = "https://xxxx"; var headers = (IDictionary<string, object>)new ExpandoObject(); headers["Cache-Control"] = "no-cache"; getEvents.Headers = headers; var batchRequest = new { GetEvents = getEvents, GetAttributes = new { Method = "GET", ParentIDs = new JArray("GetEvents"), RequestTemplate = new { Resource = "{0}?selectedFields=Items.Name;Items.Value.Value" }, Parameters = new JArray("$.GetEvents.Content.Items[*].Links.Value") } };
内容的提问来源于stack exchange,提问作者Mver
相关产品推荐
相关产品推荐

