简体   繁体   中英

Content-Type returned by HEAD request sent using C# HttpClient is incorrect; however, Postman returns the correct Content-Type

I must get the Content-Type of an URL using .NET.

However, it's returning text/html for this URL, while Postman returns the correct Content-Type video/mp4 . For several others file URLs, .NET returns the correct Content-Type, but not for this.

My code:

string uriString = "INSERT_URL_HERE";
HttpClient httpClient = new();
try
{
    HttpRequestMessage request = new(HttpMethod.Head, uriString);
    HttpResponseMessage response = await httpClient.SendAsync(request);
    response.EnsureSuccessStatusCode();

    string contentType = response.Content.Headers.ContentType.ToString();
    Console.WriteLine("\nThe Content-Type of the resource is: {0}\n", contentType);
}
catch (Exception exception)
{
    Console.WriteLine("\nException caught!");
    Console.WriteLine("Message: {0}\n", exception.Message);
}

Postman response:

邮递员回应

The problem was that the User-Agent header was not being sent, as @DiplomacyNotWar stated. After setting the User-Agent header value it worked!

PS: I used the same User-Agent of Google Chrome.

string browserUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36";
request.Headers.Add("User-Agent", browserUserAgent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM