【发布时间】:2018-11-28 07:30:31
【问题描述】:
我正在尝试获取 HTTP 响应中 Content-Type 内容标头的值。
private async void StartButton_Click(object sender, EventArgs e)
{
var client = new HttpClient();
// When I send a GET request to this website and print the response
var response = await client.GetAsync("https://www.npr.org/sections/13.7/2017/12/01/567727098/a-tax-that-would-hurt-sciences-most-valuable-and-vulnerable");
Console.WriteLine(response);
// [BELOW] You can clearly see: Content-Type: text/html;;charset=UTF-8
// However, the value is malformed (note the double semicolon) and becomes null
Console.WriteLine(response.Content.Headers.ContentType == null);
// True
}
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: no-referrer-when-downgrade
Strict-Transport-Security: max-age=604800; includeSubDomains
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Connection: keep-alive
Connection: Transfer-Encoding
Cache-Control: max-age=0
Date: Tue, 19 Jun 2018 10:38:01 GMT
Server: Apache
X-Powered-By: PHP/5.6.33
Content-Type: text/html;;charset=UTF-8
Expires: Tue, 19 Jun 2018 10:38:01 GMT
Last-Modified: Fri, 01 Dec 2017 15:41:00 GMT
}
如何修复 Content-Type 的格式错误的值,使其变为 text/html; charset=UTF-8 而不是 null?
我试图尽可能简单地解释我的问题。如果您有任何问题或认为我遗漏了什么,请告诉我! :)
【问题讨论】:
-
你不能。您需要在请求中指定 Content-Type。当您发送请求时,标头用于协商客户端和服务器之间的一组公共属性。在这种情况下,您不会发送 int 内容类型,因此服务器不知道您正在使用什么编码并返回 null。因此,将 Content-Type 添加到您的请求中。
-
你试过
response.Headers.GetValues("Content-Type")读吗? -
@Crowcoder 你引导我找出答案,虽然它看起来不必要的草率。
标签: c# http-headers httprequest httpresponse response-headers