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

查看:384
本文介绍了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 ...}

得到的结果:{高: 690.00,最后: 645.10,时间戳: 1387715532 ...}

...

got result: {"high": "690.00", "last": "645.10", "timestamp": "1387715532" ... }
got result: {"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天全站免登陆