网站建设试用,建设部注册人员查询,宁波网站建设运营,杭州律师由于在用wpf开发应用程序时#xff0c;从后端获取数据需要用到 Authorization 授权的Bearer令牌#xff0c;而这个令牌的获取需要登录后台进行获取#xff0c;这里登录时还涉及到的验证码的操作#xff0c;所以在获取过程中#xff0c;需要对后台系统进行登录并拿到这个Be…
由于在用wpf开发应用程序时从后端获取数据需要用到 Authorization 授权的Bearer令牌而这个令牌的获取需要登录后台进行获取这里登录时还涉及到的验证码的操作所以在获取过程中需要对后台系统进行登录并拿到这个Bearer令牌。
1 登录
正确的登录方式一般包括用户名、密码和验证码其中验证码是随机生成的而且显示的是图片当前测试使用到的是后端转成base64格式的字符串传过来然后再在前端显示这样一个过程。
1.1 验证码获取
直接打开对应的url地址进行code获取定义异步任务返回获取到的内容。
public async Taskstring GetCodeAsyncT()
{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.GetCodeAsyncHttpsMessages.MyResponseType();JObject jObject JObject.Parse(result);
JToken img jObject[img];
JToken uuid jObject[uuid];
strImg img.ToString();
struuid uuid.ToString();
1.2 Base64转图片显示
在WPFWindows Presentation Foundation中显示Base64编码的图片你可以使用Image控件并将图片的Base64字符串转换为BitmapImage。以下是一个完整的示例代码展示了如何实现这一功能。
步骤一 在XAML中添加Image控件
首先在你的项目中添加一个Image控件用于显示图片
Image x:NameBase64Image Grid.Column1 StretchUniform HorizontalAlignmentLeft VerticalAlignmentTop Width150 Height50 Margin450,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;
注意事项
Base64字符串格式确保你的Base64字符串是正确的并且如果包含MIME类型前缀如data:image/png;base64,你需要将其移除。线程安全在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.GetBearerTokenAsyncHttpsMessages.MyResponseType(strCode, strUserName, strPassword, struuid);MessageBox.Show($令牌为{result});
}public async Taskstring GetBearerTokenAsyncT(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 Taskstring GetAsyncT(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});}