3

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.

Panup Pong
  • 1,871
  • 2
  • 22
  • 44
David Nordvall
  • 12,404
  • 6
  • 32
  • 52

1 Answers1

3

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

Community
  • 1
  • 1
Alex Lyalka
  • 1,484
  • 8
  • 13
  • 1
    Unfortunately this doesn't work. Even though the delegating handlers executes, the call to `base.SendAsync()` fails with the same `FormatException` as earlier. – David Nordvall Jan 02 '18 at 13:13