好的,所以我有这个API,我想在应用程序启动后第二次将其加载到我的后台,我会初始化请求。但是我不会在任何地方调用异步任务,并且我不想为此使用按钮。我有自己的类,它将接收来自响应的数据,但我只希望将其移交给另一种方法,以便可以在其中使用它,而不必向用户显示数据。我应该怎么做?这是我来自Mainwindow.xaml.cs和API.cs的代码 答案 0 :(得分:0) 在视图模型中,创建一个调用该方法并使用结果的命令 在XAML中,将命令挂接到窗口的Loaded事件 答案 1 :(得分:0) 在您的用例场景中,异步生产者使用者设计模式看起来可能很有用,并且为了支持您可以考虑使用dotnet核心框架上可用的通道。
您的生产者将是执行http请求的Class,然后它将响应发送到a通道中,以便消费者类获取该数据并执行所需的任何操作。
这是simple example的概念,用于理解生产者消费者和渠道周围的概念。using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestAPi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Api.InitializeClient("");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestAPi
{
public class Api
{
private static HttpClient ApiClient { get; set;}
private string url { get; set;}
public static void InitializeClient(string token)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("your url");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Bearer Authentication"));
}
public async Task<Data> LoadData()
{
url = ApiClient.BaseAddress.ToString();
using (HttpResponseMessage response = await ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
Data data = await response.Content.ReadAsAsync<data>();
return data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
2 个答案:
public AsyncCommand LoadCommand { get; }
// in constructor
LoadCommand = new AsyncCommand(LoadAndUse);
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>