自学内容网 自学内容网

【wpf】07 后端验证及令牌码获取步骤

在这里插入图片描述
在这里插入图片描述

由于在用wpf开发应用程序时,从后端获取数据需要用到 Authorization 授权的Bearer令牌,而这个令牌的获取需要登录后台进行获取,这里登录时还涉及到的验证码的操作,所以在获取过程中,需要对后台系统进行登录并拿到这个Bearer令牌。

1 登录

正确的登录方式,一般包括用户名、密码和验证码,其中验证码是随机生成的,而且显示的是图片,当前测试使用到的是后端转成base64格式的字符串传过来,然后再在前端显示,这样一个过程。

1.1 验证码获取

直接打开对应的url地址进行code获取,定义异步任务,返回获取到的内容。

public async Task<string> GetCodeAsync<T>()
{
    HttpResponseMessage response = await httpClient.GetAsync("Your url");
    if (response.IsSuccessStatusCode)
    {
        string content = await response.Content.ReadAsStringAsync();
        return content;
    }

    throw new Exception($"Error getting data from API: {response.StatusCode}");
}

一般Get到的数据是Json格式,这里拿到数据之后需要用Json转换一下,来拿到我们需要的数据

HttpsMessages httpMessage = new HttpsMessages();
var result = await httpMessage.GetCodeAsync<HttpsMessages.MyResponseType>();

JObject jObject = JObject.Parse(result);
JToken img = jObject["img"];
JToken uuid = jObject["uuid"];
strImg = img.ToString();
struuid = uuid.ToString();

1.2 Base64转图片显示

在WPF(Windows Presentation Foundation)中显示Base64编码的图片,你可以使用Image控件并将图片的Base64字符串转换为BitmapImage。以下是一个完整的示例代码,展示了如何实现这一功能。

步骤一: 在XAML中添加Image控件

首先,在你的项目中添加一个Image控件,用于显示图片


 <Image x:Name="Base64Image" Grid.Column="1" Stretch="Uniform" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150" Height="50" Margin="450,340,0,0"/>

步骤二:在后台代码中加载Base64图片

在窗口加载时(例如在Window_Loaded事件处理程序中)将Base64字符串转换为BitmapImage并赋值给Image控件的Source属性。
示例代码(这里拿到的数据是从后端Get到后通过Json解析后的数据):

// 将Base64字符串转换为字节数组  
byte[] imageBytes = Convert.FromBase64String(strImg);

// 使用字节数组创建BitmapImage  
BitmapImage bitmapImage = new BitmapImage();
using (var ms = new System.IO.MemoryStream(imageBytes))
{
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = ms;
    bitmapImage.EndInit();
    bitmapImage.Freeze(); // 使BitmapImage只读,以便可以在多个线程之间共享  
}

// 将BitmapImage设置为Image控件的Source  
Base64Image.Source = bitmapImage;

注意事项:

  1. Base64字符串格式:确保你的Base64字符串是正确的,并且如果包含MIME类型前缀(如data:image/png;base64,),你需要将其移除。
  2. 线程安全:在WPF中,某些UI元素(如BitmapImage)需要在UI线程上进行操作。上面的代码示例已经处理了这一点,通过Freeze()方法使BitmapImage成为只读对象,从而可以在多个线程之间共享。
    通过上述步骤,就可以在WPF应用程序中成功显示Base64编码的图片。

1.3 验证并获取Bearer令牌码

以上的操作只是从后端拿到了验证码部分,接下来我们需要输入账号、密码和验证码发送给后端进行验证,进而拿到我们需要的Bearer令牌码,这里需要发送四个值,分别是验证码、用户名、密码和uuid
示例代码:

 HttpsMessages httpMessage = new HttpsMessages();
 if (null != txtBoxCode.Text)
 {
     string strCode = txtBoxCode.Text;
     var result = await httpMessage.GetBearerTokenAsync<HttpsMessages.MyResponseType>(strCode, strUserName, strPassword, struuid);

     MessageBox.Show($"令牌为:{result}");
}

public async Task<string> GetBearerTokenAsync<T>(string code ,string userame,string password,string uuid)
{
    // 构造JSON格式的登录请求体  
    var json = new StringContent( 
        $"{{\"code\": \"{code}\",\"username\": \"{userame}\", \"password\": \"{password}\", \"uuid\": \"{uuid}\"}}",  
        Encoding.UTF8, 
        "application/json");
    // 发送POST请求并等待响应
    HttpResponseMessage response = await httpClient.PostAsync("Your url", json);

    // 确保响应成功  
    response.EnsureSuccessStatusCode();

    // 读取响应内容
    string responseBody = await response.Content.ReadAsStringAsync();

    JObject jObject = JObject.Parse(responseBody);
    string retCode = jObject["code"].ToString();
    if(retCode == "500")
    {
        return null;
    }
    else if(retCode == "200")
    {
        bearerToken = jObject["data"]["access_token"].ToString();
// 授权
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
        return bearerToken;
    }
    throw new Exception($"Error getting data from API: {response.StatusCode}");
}

拿到令牌后,将其赋值给全局变量,在进行后面的数据获取时,将这个令牌进行授权即可实现。

2 数据获取

在执行异步获取数据时,将授权执行一次即可。
示例代码:

 public async Task<string> GetAsync<T>(string path,string bearerToken)
 {
     httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);

     HttpResponseMessage response = await httpClient.GetAsync("Your url");
     if (response.IsSuccessStatusCode)
     {
         string content = await response.Content.ReadAsStringAsync();
         return content;
     }

     throw new Exception($"Error getting data from API: {response.StatusCode}");
 }


原文地址:https://blog.csdn.net/kewaqi618/article/details/143054084

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!