FoxNet FoxNet - 1 year ago 126
HTTP Question

UWP HttpClient disable "If" headers

I found one interesting feature in UWP and HttpClient (it also works with WebRequest) :
Any Http request sends "If-*" headers. I did experiment with UWP and WPF apps. I sent request to Azure file storage which doesn't support "If-" headers and will return Error 400 if headers will be sended. So here is my code:

HttpClient client = new HttpClient();
var response = await client.GetAsync("LINK_TO_AZURE_FILE_STORAGE_IMAGE");

Very simply, similar for two apps. Result - WPF app doesn't send "If-*" headers, UWP does. So It means that I'm not able to use File Storage in UWP apps, I just have Error 400.

My question is - can I disable this st...d caching ? Thanks for your attention

Answer Source

Yeah, while using HttpClient in UWP apps, it will automatically use the local HTTP cache by default. For the first time, you code should work. Then you will get 400 Error as in the first response, it contains cache data and all subsequent requests will use this cache by default like following:
enter image description here

To fix this issue, we can use Windows.Web.Http.HttpClient class with HttpBaseProtocolFilter class and HttpCacheControl class to disable the cache like following:

var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

var httpClient = new Windows.Web.Http.HttpClient(filter);

var response = await httpClient.GetAsync(new Uri("LINK_TO_AZURE_FILE_STORAGE_IMAGE"));

To make this method work, we need make sure there is no local HTTP cache. As HttpCacheReadBehavior.MostRecent represents it will still use the local HTTP cache if possible. So we'd better uninstall the app first and do not use HttpClient client = new HttpClient(); in the app.