问题:
最近研究对接易微联的“酷宅开放平台4.2”,其中v2接口通用参数有要求:
Content-Type:固定为 "application/json" or "application/json; charset=utf-8"
Host:大部分 HTTP 客户端会自动添加此字段,如果没有,必须代码明确指定,值为对应的接口域名,比如: cn-apia.coolkit.cn, us-apia.coolkit.cc
我的解决方案:
我想当然以为直接在http header中设置就可以了,写了以下代码:
Dictionary<string, string> header = new Dictionary<string, string>();
header.Add("X-CK-Appid", clientId);
header.Add("Authorization", $"Sign {sign}");
header.Add("Content-Type", "application/json");
header.Add("Host", "cn-apia.coolkit.cn");
if (headers != null && headers.Count > 0)
{
request.Headers = new WebHeaderCollection();
foreach (var head in headers.Keys)
{
request.Headers.Add(head, headers[head]);
}
}
结果却报错了。
提示:<Message>出现错误。</Message>
<ExceptionMessage>必须使用适当的属性或方法修改“Content-Type”标头。 参数名: name</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
原因:
在Asp.Net中http协议的Headers请求都设置时,部分协议定义的属性已经封装,不能使用Add方法自定义提交。c#已经提供了此类标头的专用属性。
解决方案:
直接通过request的属性进行设置,且必须在设置完毕headers后再设置。
if (headers != null && headers.Count > 0)
{
request.Headers = new WebHeaderCollection();
foreach (var head in headers.Keys)
{
request.Headers.Add(head, headers[head]);
}
}
request.ContentType = ContentType;
request.Host = "cn-apia.coolkit.cn";
这个问题在.net6中没有出现。在.net Framework中会出现。