WebClient/HttpClient 的缓存问题 [英] Caching issue with WebClient/HttpClient

查看:51
本文介绍了WebClient/HttpClient 的缓存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个代码,每 30 秒轮询一次 Bitstamp 交易代码.这是我的代码:

I'm developing a code to poll a Bitstamp exchange ticker every 30 seconds. This is a code I have:

public IObservable<string> Stream(Uri way, WebClient wc)
    {
        Func<IObserver<string>, Task> Fun = async Observer =>
        {
            var res = await wc.DownloadStringTaskAsync(way);
            Observer.OnNext(value: res);
        };

        return Observable.Create<string>(Fun);
    }

public IObservable<string> GetDelay(int secs)
    {
        var exe = TimeSpan.FromSeconds(secs);
        return Observable.Empty<string>("x").Delay(exe);
    }

Stream(new Uri("https://bitstamp.net/api/ticker"), new WebClient { }).Concat(GetDelay(30))
    .Repeat(5).Subscribe(res => Debug.WriteLine("got result: {0}", res));

问题是WebClient(以及HttpClient)在第一次调用后都返回缓存的结果,可以通过相同的时间戳看到:

The problem is that WebClient (and HttpClient, too) both return cached results after the first call, it can be seen by the same timestamp:

得到结果:{"high": "690.00", "last": "645.10", "timestamp": "1387715532" ... }
得到结果:{"high": "690.00", "last": "645.10", "timestamp": "1387715532" ... }
...

即使在关闭网络后,他们也会正常返回结果,因此很明显他们将其缓存在某处.添加诸如?cache=random"之类的内容不起作用,因为 Bitstamp 上的代码不允许请求参数.为 WebRequest 设置 Headers[HttpRequestHeader.CacheControl] = "no-cache" 也不起作用.

Even after turning the networks off they return the result normally so obviously they cache it somewhere. Adding something like "?cache=random" does not work because request parameters are not allowed for ticker on Bitstamp. Setting Headers[HttpRequestHeader.CacheControl] = "no-cache" for WebRequest does not work either.

如何修复这种奇怪的缓存行为?

How can I fix this weird caching behavior?

推荐答案

通过在每次后续调用之前设置 wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(); 解决.

Solved by setting wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(); before each subsequent call.

这篇关于WebClient/HttpClient 的缓存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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