是否可以让 HttpClient 在响应中忽略无效的 ETag 标头? [英] Is it possible to make HttpClient ignore invalid ETag header in response?

查看:26
本文介绍了是否可以让 HttpClient 在响应中忽略无效的 ETag 标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,该应用程序使用 HttpClient API 向我无法控制的第三方服务发出 Web 服务请求.根据 HTTP 规范,该服务似乎使用包含无效值的 ETag HTTP 标头响应请求(该值未用引号括起来).这会导致 HttpClientSystem.FormatException 失败.

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.

在这种情况下,我对 ETag 标头不感兴趣,希望能够忽略无效值.是否可以使用 HttpClient 来做到这一点?

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?

我更喜欢使用 HttpClient API 而不是 WebClientWebRequest 因为这个特殊用例要求我使用 SOCKS 代理使用 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.

推荐答案

试试这个:

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;
    }
}

我的响应头:

HTTP/1.1 200 正常

HTTP/1.1 200 OK

日期:2013 年 1 月 25 日星期五 16:49:29 GMT

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

FiddlerTemplate:真

FiddlerTemplate: True

内容长度:310

内容类型:图片/gif

Content-Type: image/gif

电子标签:rtt123

ETag: rtt123

这篇关于是否可以让 HttpClient 在响应中忽略无效的 ETag 标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆