0

使用 Visual Studio 的 Template Studio 扩展,我生成了一个项目解决方案库,现在我尝试在继续呈现页面视图之前使用 HTTP 请求插入应用程序加载过程。

应用程序.xaml.cs

using System;

using Braytech_3.Services;

using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.UI.Xaml;

namespace Braytech_3
{
    public sealed partial class App : Application
    {
        private Lazy<ActivationService> _activationService;

        private ActivationService ActivationService
        {
            get { return _activationService.Value; }
        }

        public App()
        {
            InitializeComponent();

            APIRequest();

            // Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class.
            _activationService = new Lazy<ActivationService>(CreateActivationService);
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!args.PrelaunchActivated)
            {
                await ActivationService.ActivateAsync(args);
            }
        }

        protected override async void OnActivated(IActivatedEventArgs args)
        {
            await ActivationService.ActivateAsync(args);
        }

        private async void APIRequest()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                APITempSave(httpResponseBody);

            }
            catch (Exception ex)
            {

            }
        }

        private async void APITempSave(string json)
        {
            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

            if (await tempFolder.TryGetItemAsync("APIData.json") != null)
            {
                StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }
            else
            {
                StorageFile APIData = await tempFolder.CreateFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }

        }

        private ActivationService CreateActivationService()
        {
            return new ActivationService(this, typeof(Views.VendorsPage), new Lazy<UIElement>(CreateShell));
        }

        private UIElement CreateShell()
        {
            return new Views.ShellPage();
        }
    }
}

我认为我需要做的是调用_activationService = new Lazy<ActivationService>(CreateActivationService);一次APITempSave(),但我不确定如何这样做以及最佳实践是什么。

任何指导将不胜感激!

4

1 回答 1

1

在对生成的解决方案进行进一步调查和熟悉后,以及对 await、async 和 Tasks<> 的额外谷歌搜索后,我能够将请求作为服务与 ThemeSelector 和 ToastNotifications 等项目一起实现。

ThemeSelector 是为确定当前用户的明暗主题模式而首先调用的对象之一,因此我能够围绕它对我的服务进行建模并同时调用它。

这显然非常特定于模板工作室生成的代码,但有些概念是共享的,如果其他人在未来寻找类似的答案,也许他们会找到这个。

APIRequest.cs(服务)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace Braytech_3.Services
{
    public static class APIRequest
    {

        internal static async Task Request()
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            Uri requestUri = new Uri("https://json_url");

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                await APITempSave(httpResponseBody);

            }
            catch (Exception ex)
            {

            }
        }

        internal static async Task APITempSave(string json)
        {
            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;

            if (await tempFolder.TryGetItemAsync("APIData.json") != null)
            {
                StorageFile APIData = await tempFolder.GetFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }
            else
            {
                StorageFile APIData = await tempFolder.CreateFileAsync("APIData.json");
                await FileIO.WriteTextAsync(APIData, json);
            }

        }
    }
}

ActiviationService.cs(最初由 App.xaml.cs 调用)

private async Task InitializeAsync()
{
    await ThemeSelectorService.InitializeAsync();
    await APIRequest.Request();
}
于 2018-10-09T03:27:26.610 回答