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

放肆的年华 提交于 2020-06-27 14:47:31

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/47691177/is-it-possible-to-make-httpclient-ignore-invalid-etag-header-in-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!