MVC 4 WebRequest WebResponse缓存

时间:2016-08-05 07:40:57

标签: asp.net-mvc caching

我正在尝试禁用页面上的缓存。原因 - 相关页面应显示每个请求的最新数据,数据来自外部XML Feed。

我正在使用标准的HttpWebRequest HttpWebResponse。一切正常,但我得到了一些(我相信)缓存问题,通过直接查询XML提要URL,我得到的数据与使用相同网址的Controller / View数据相比更新。

XML feed URL在每个请求上附加了随机数,并且在控制器中禁用了缓存([OutputCache(NoStore = true,Duration = 0)])以及ActionResult,它产生以下内容:

响应 HTTP / 1.1 200好的 缓存控制:无缓存,无存储,必须重新验证 Pragma:没有缓存 内容类型:text / html;字符集= utf-8的 到期:-1 服务器:Microsoft-IIS / 10.0 X-AspNetMvc-Version:5.1 X-AspNet-Version:4.0.30319 X-Frame-Options:SAMEORIGIN X-Powered-By:ASP.NET X-UA兼容:IE =边缘 日期:星期四,2016年8月4日13:22:33 GMT 内容长度:75285

请求 漂亮的印花 GET /投资者关系/股价HTTP / 1.1 主持人:cms.crestnicholson-dev.com User-Agent:Mozilla / 5.0(Windows NT 10.0; WOW64; rv:47.0)Gecko / 20100101 Firefox / 47.0 接受:text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8 Accept-Language:en-GB,en; q = 0.5 Accept-Encoding:gzip,deflate Cookie:ecos.dt = 1470316952533; ASP.NET_SessionId = 5lbh4v20kac0boadibjfwedr; IsAgreeToCookiePolicy =真 连接:保持活力 Pragma:没有缓存 缓存控制:无缓存

仍然过时/缓存的数据在页面上呈现......

如果有人有任何想法/建议,我们将不胜感激。

控制器代码:

    [OutputCache(NoStore = true, Duration = 0)]
public class InvestorRelationsController : Controller
{
    public ActionResult SharePrice()
    {
        Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        Response.Cache.SetValidUntilExpires(false);
        Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();

        return PartialView(GetSharePrice());
    }

    private SharePriceModel GetSharePrice()
    {
        try
        {
            var xml = GetSharePriceXml();
            return ParseSharePrice(xml);
        }
        catch (Exception)
        {
            return new SharePriceModel() {IsServiceUnavailable = true};
        }
    }

    private SharePriceModel ParseSharePrice(string xml)
    {
        Guard.ArgumentNotNull(xml, "xml");
        var model = new SharePriceModel();

        var doc = new XmlDocument();
        doc.Load(new StringReader(xml));
        var root = doc.DocumentElement;
        model.DateLastUpdated = root.SelectSingleNode("Time").InnerText;
        model.Price = root.SelectSingleNode("CurrentPrice").InnerText;
        model.Change = root.SelectSingleNode("Change").InnerText;
        model.ChangePersentage = root.SelectSingleNode("PercentageChange").InnerText;

        return model;
    }

    private string GetSharePriceXml()
    {
        Uri address = new Uri(SiteConfiguration.SharePriceFeedUrl);

        Random random = new Random();
        string url = address + "?random=" + random.Next();

        // Set a default policy level for the "http:" and "https" schemes.
        HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
        HttpWebRequest.DefaultCachePolicy = policy;
        HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

        // Create the web request
        var request = WebRequest.Create(url) as HttpWebRequest;
        // Set type to POST
        request.CachePolicy = noCachePolicy;
        request.KeepAlive = false; 
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";

        request.Headers.Add("Cache-Control", "no-cache");
        request.Headers.Add("Cache-Control", "private");

        // Get response
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                // Console application output
                return reader.ReadToEnd().Trim();
            }
        }
    }
}

0 个答案:

没有答案