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

Ali*_*123 1 c# httpclient pragma cache-control xamarin.forms

我添加了这一行以在 HTTP 客户端中不应用缓存

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.CacheControl.NoCache = true;
Run Code Online (Sandbox Code Playgroud)

当我运行之前运行良好的应用程序时,我在第二行中收到此异常:

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

我试过这是应用运行良好的 NoChache 标志,但我不确定它是否符合预期。

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

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

Min*_*ipe 6

看起来在实例化一个新的时HttpClientCacheControl被设置为null. 您的解决方案是将 设置CacheControl为不缓存的一种方法,但这是一种不那么冗长的方法:

HttpClient httpClient = new HttpClient();
client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue {NoCache = true};
Run Code Online (Sandbox Code Playgroud)

编辑:更正拼写错误