WP8.1 HttpClient在第一次请求后不下载字符串

时间:2015-12-02 19:41:01

标签: c# windows-phone-8.1 async-await httpclient

我想知道发生了什么事。我正在为Windows Phone 8.1编写一个应用程序,它使用HttpClient从Internet下载json字符串。它在运行应用程序后只运行一次(在OnNavigatedTo事件中)。稍后,粉碎“刷新”按钮应该再次下载字符串不起作用。它仍然是首先下载的相同字符串值。在服务器上,这个字符串发生了变化,我可以通过在PC上的浏览器中查看它来确认。

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace WP8App
{
    public sealed partial class MainPage : Page
    {
        private readonly Uri Website = new Uri("https://some-website.com/files/status.json");
        private HttpClient http = new HttpClient();

        public MainPage()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Refresh();
        }

        private async void Button_Refresh_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        private async void Refresh()
        {
            var response = await http.GetStringAsync(Website);
            JsonObject api = JsonConvert.DeserializeObject<JsonObject>(response);
            TextBox_A.Text = api.value;
            TextBox_B.Text = api.length;
            TextBox_C.Text = api.size;
            TextBox_F.Text = api.volume;
        }

        private async void ShowDialog(string value)
        {
            MessageDialog box = new MessageDialog(value);
            await box.ShowAsync();
        }
    }
}

我不是异步的高手,所以我依靠你的鹰眼xD谢谢

1 个答案:

答案 0 :(得分:0)

请求缓存在Windows Phone上非常激进。绕过它的最简单方法是在URL的末尾添加一个随机参数。类似的东西:

private readonly string Website = "https://some-website.com/files/status.json?nocache={0}";

然后每次使用时更改值。使用当前时间戳是确保URL始终不同的一种便宜的好方法:

var response = await http.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks));