.NET MAUI实现RESTful API POST获取access_token的入门疑问
.NET MAUI安卓获取Token并验证账号分步教程
核心问题解答
必须创建与Postman请求Body参数对应的实体类,JsonContent.Create<Part>(part)需要通过强类型对象将参数序列化为符合接口要求的JSON格式,确保参数名、类型和必填项完全匹配接口定义。
分步实现教程
1. 创建POST请求参数实体类
根据Postman里的必填参数定义实体类,比如假设你的POST请求Body包含grant_type、username、password、client_id四个必填项,实体类代码如下:
using System.Text.Json.Serialization; public class TokenRequestModel { [JsonPropertyName("grant_type")] // 必须和接口字段名完全一致,大小写敏感 public string GrantType { get; set; } = "password"; // 密码模式通常固定为该值 [JsonPropertyName("username")] public string Username { get; set; } = string.Empty; [JsonPropertyName("password")] public string Password { get; set; } = string.Empty; [JsonPropertyName("client_id")] public string ClientId { get; set; } = string.Empty; }
提示:如果接口有其他参数,直接添加对应属性并标记
JsonPropertyName即可。
2. 创建Token响应实体类
接口返回的access_token通常包含固定字段,定义实体类方便解析:
public class TokenResponseModel { [JsonPropertyName("access_token")] public string AccessToken { get; set; } = string.Empty; [JsonPropertyName("token_type")] public string TokenType { get; set; } = string.Empty; [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; } }
3. 发送POST请求获取Token
在.NET MAUI中推荐先在MauiProgram.cs注册单例HttpClient:
// MauiProgram.cs builder.Services.AddHttpClient();
然后在ViewModel或页面后台注入HttpClient实现请求逻辑:
using System.Net.Http.Json; public class AccountViewModel { private readonly HttpClient _httpClient; // 构造函数注入HttpClient public AccountViewModel(HttpClient httpClient) { _httpClient = httpClient; _httpClient.BaseAddress = new Uri("https://你的接口域名/"); // 设置接口基础地址 } public async Task<string> GetAccessToken(string username, string password) { try { var tokenRequest = new TokenRequestModel { Username = username, Password = password, ClientId = "你的客户端ID" // 替换为实际值 }; var response = await _httpClient.PostAsJsonAsync("api/auth/token", tokenRequest); response.EnsureSuccessStatusCode(); // 确保请求成功 var tokenResponse = await response.Content.ReadFromJsonAsync<TokenResponseModel>(); return tokenResponse?.AccessToken ?? string.Empty; } catch (HttpRequestException ex) { Console.WriteLine($"获取Token失败: {ex.Message}"); return string.Empty; } } }
4. 使用Token调用GET验证接口
拿到access_token后,在GET请求Header中添加授权信息:
public async Task<bool> VerifyAccount(string accessToken) { if (string.IsNullOrEmpty(accessToken)) return false; try { var request = new HttpRequestMessage(HttpMethod.Get, "api/auth/verify"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); var response = await _httpClient.SendAsync(request); return response.IsSuccessStatusCode; } catch (HttpRequestException ex) { Console.WriteLine($"验证账号失败: {ex.Message}"); return false; } }
5. 在页面中调用方法
比如在登录按钮点击事件中执行流程:
private async void LoginButton_Clicked(object sender, EventArgs e) { // 若使用依赖注入,直接从容器获取ViewModel即可 var viewModel = new AccountViewModel(HttpClientFactory.CreateClient()); var token = await viewModel.GetAccessToken(UsernameEntry.Text, PasswordEntry.Text); if (!string.IsNullOrEmpty(token)) { bool isVerified = await viewModel.VerifyAccount(token); if (isVerified) { await Navigation.PushAsync(new MainPage()); } else { await DisplayAlert("错误", "账号验证失败", "确定"); } } else { await DisplayAlert("错误", "获取Token失败", "确定"); } }
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

