David Nordvall
David Nordvall

Reputation: 13202

Is it possible to make HttpClient ignore invalid ETag header in response?

I'm working on an application which makes a web service request using the HttpClient API to a third party service over which I have no control. The service seems to respond to requests with an ETag HTTP header containing an invalid value according to the HTTP specification (the value is not enclosed in quotation marks). This causes the HttpClient to fail with a System.FormatException.

In this case I am not interested in the ETag header and would like to be able to ignore the invalid value. Is it possible to do this using HttpClient?

I would prefer to use the HttpClient API over WebClient or WebRequest since this particular use case requires me to use a SOCKS proxy which is a lot simpler when using HttpClient.

Upvotes: 4

Views: 1319

Answers (1)

Alex Lyalka
Alex Lyalka

Reputation: 1641

Try this:

class Example
{
    static void Main()
    {
        var client = HttpClientFactory.Create(new Handler());
        client.BaseAddress = new Uri("http://www.example.local");
        var r = client.GetAsync("").Result;
        Console.WriteLine(r.StatusCode);
        Console.WriteLine(r.Headers.ETag);
    }
}

class Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var headerName = "ETag";
        var r = await base.SendAsync(request, cancellationToken);
        var header = r.Headers.FirstOrDefault(x => x.Key == headerName);
        var updatedValue = header.Value.Select(x => x.StartsWith("\"") ? x : "\"" + x + "\"").ToList();
        r.Headers.Remove(headerName);
        r.Headers.Add(headerName, updatedValue);
        return r;
    }
}

My response headers:

HTTP/1.1 200 OK

Date: Fri, 25 Jan 2013 16:49:29 GMT

FiddlerTemplate: True

Content-Length: 310

Content-Type: image/gif

ETag: rtt123

Upvotes: 4

Related Questions