You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WPF中使用Token授权访问数据并展示至DataGrid

WPF登录授权后DataGrid展示数据实现

我有一个具备登录和注册功能的API,用户登录后可获取Token。我希望在通过该Token完成授权后,WPF中的DataGrid能够展示对应数据。以下是我编写的授权按钮与登录按钮的代码,期望实现登录后点击「授权」按钮即可在表格中看到数据:

授权按钮代码

private async void btn_Authorize_Click(object sender, RoutedEventArgs e)
{
    var httpClient = new HttpClient();
    string token = txt_Code.Text;

    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var response = await httpClient.GetAsync("https://localhost:7085/Picture");

    if (response.IsSuccessStatusCode)
    {
        var pictures = await response.Content.ReadFromJsonAsync<List<Picture>>();
        dtg_Pictures.ItemsSource = pictures;
    }
}

登录按钮代码

private async void btn_Login_Click(object sender, RoutedEventArgs e)
{
    var httpClient = new HttpClient();

    var user = new User()
    {
        Username = txt_Name.Text,
        Password = txt_Password.Text
    };

    var response = await httpClient.PostAsJsonAsync("https://localhost:7085/api/Auth/Login", user);

    if (response.IsSuccessStatusCode)
    {
        var wpfServiceResponse = await response.Content.ReadFromJsonAsync<ServiceResponse<string>>();
        if (wpfServiceResponse != null && wpfServiceResponse.Success)
        {
            string data = wpfServiceResponse.Data!;
            txt_Code.Text = data;
        }
    }
}

内容的提问来源于stack exchange,提问作者Deivydas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:25:03