HTTP客户端NoCache标志导致空引用异常C#[重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

我添加了这一行,以便在HTTP Client中不应用缓存

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.CacheControl.NoCache = true;

当我运行之前工作正常的应用程序时,我在第二行得到此异常:

NullReferenceException:未将对象引用设置为对象的实例

我试过这是应用NoChache标志运行正常,但我不确定它是否做到了预期。

HttpClient httpClient = new HttpClient()
{ 
    DefaultRequestHeaders=
    { 
        CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store"),
        Pragma = { NameValueHeaderValue.Parse("no-cache")}
    }
};

请帮我应用正确的方法来设置NoCache标志。

c# xamarin.forms httpclient cache-control pragma
1个回答
2
投票

看起来当实例化一个新的HttpClient时,它的CacheControl被设置为null。你的解决方案是一种将CacheControl设置为不缓存的方法,但这是一种不那么冗长的方式:

HttpClient httpClient = new HttpClient();
client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue {NoCache = true};

编辑:更正拼写错误

© www.soinside.com 2019 - 2024. All rights reserved.