Search code examples
c#httpclient

Unable to get the Last-Modified header from the response


I am trying to get the Last-Modified header from the response, but I keep getting the Unhandled exception. System.InvalidOperationException: Misused header name, 'Last-Modified'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects. error.

What is wrong and how to fix this?

// using System.Net.Http.Headers;

var url = "http://example.com";
using var client = new HttpClient();
// client.DefaultRequestHeaders.Add("Content-Type", "application/json;charset=UTF-8");
// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var res = await client.GetAsync(url);
Console.WriteLine();

// if (res.Headers.Contains("Last-Modified"))
// {
//     var hdate = res.Headers.GetValues("Last-Modified").First();
//     var dt = DateTime.Parse(hdate);
//     Console.WriteLine(dt);
// }

string? lm = res.Headers.GetValues("Last-Modified").FirstOrDefault();

// var hdate = res.Headers.Date;

Solution

  • Console.WriteLine(res.Content.Headers.LastModified);