[英]How to set "custom" Content-Type of an HttpClient request in DOT NET CORE?
我正在尝试根据我正在调用的 API 的要求将 Content-Type 设置为 HttpClient 请求的“application/x.example.hr.employee.email+json;version=1” 。 API 是GET类型并接受JSON 正文(包含电子邮件列表)。
我成功地将Accept header 设置为"application/x.example.hr.employee+json;version=1" 。 在这种情况下,-Accept 和 Content-Type 都需要按照上述设置,否则 API 会抛出错误 400(错误请求)。 我试过How do you set the Content-Type header for an HttpClient request? 和其他几个选项,但是当我尝试设置 Content-Type 而不是"application/json"时出现运行时错误。
该类型需要应用在请求内容上,而不是在 header Content-Type 中。 以下是我尝试过的代码片段之一:
_httpClient.BaseAddress = new Uri("http://example.com/");
_httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/x.example.hr.employee+json;version=1");
//_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x.example.hr.employee.email+json;version=1"); // Throws exception
List<string> strEmail = new List<string>
{
employeeEmail
};
var jsonEmail = JsonConvert.SerializeObject(strEmail);
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri("http://example.com/employees"),
Content = new StringContent(jsonEmail, Encoding.UTF8, "application/x.example.hr.employee.email+json;version=1")
};
//var response = _httpClient.SendAsync(request).ConfigureAwait(false);
await _httpClient.SendAsync(request)
.ContinueWith(responseTask =>
{
var response = responseTask;
});
出于不完全理解的原因,无论何时构建StringContent
(或实际上是MediaTypeHeaderValue
), "application/x.example.hr.employee.email+json;version=1"
媒体类型都无法正确解析。
我确实找到了解决方法:
List<string> strEmail = new List<string> {
employeeEmail
};
var jsonEmail = JsonConvert.SerializeObject(strEmail);
var content = new StringContent(jsonEmail, Encoding.UTF8);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x.example.hr.employee.email+json");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("version", "1"));
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri("http://example.com/employees"),
Content = content
};
奇怪的是, MediaTypeHeaderValue
构造函数(这是StringContent
调用的)不接受“application/x.example.hr.employee.email+json;version=1”。
但是, MediaTypeHeaderValue.Parse
可以。
var contentType = MediaTypeHeaderValue.Parse("application/x.example.hr.employee.email+json; version=1");
var content = new StringContent(jsonEmail, Encoding.UTF8, contentType);
如果您卡在 .NET 6 及以下:
var content = new StringContent(jsonEmail, Encoding.UTF8);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x.example.hr.employee.email+json; version=1");
请参阅此 GitHub 问题进行讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.