ASP.NET Razor Page调用Web API成功后如何反序列化JSON响应
解决ASP.NET Razor页面中Web API响应反序列化问题
1. 创建匹配JSON结构的模型类
首先需要定义两个类,分别对应API返回的根响应结构和嵌套的用户数据结构:
// 根响应模型 public class ApiLoginResponse { public string message { get; set; } public bool status { get; set; } public UserData data { get; set; } public string statusCode { get; set; } } // 用户数据模型 public class UserData { public string userID { get; set; } public string userName { get; set; } public string userRole { get; set; } public string environment { get; set; } }
如果你的项目习惯用PascalCase命名(比如UserId而非userID),可以给属性加上JsonPropertyName特性匹配JSON键名:
using System.Text.Json.Serialization; public class ApiLoginResponse { [JsonPropertyName("message")] public string Message { get; set; } [JsonPropertyName("status")] public bool Status { get; set; } [JsonPropertyName("data")] public UserData Data { get; set; } [JsonPropertyName("statusCode")] public string StatusCode { get; set; } } public class UserData { [JsonPropertyName("userID")] public string UserId { get; set; } [JsonPropertyName("userName")] public string UserName { get; set; } [JsonPropertyName("userRole")] public string UserRole { get; set; } [JsonPropertyName("environment")] public string Environment { get; set; } }
2. 修改Razor页面的API调用代码
在response.IsSuccessStatusCode判断块中,读取响应内容并反序列化,验证条件后提取用户信息:
public async Task OnPost() { UserLoginViewModel loginview = new UserLoginViewModel(); loginview.UserID = User.UserName; loginview.Password = User.vPassword; var json = JsonSerializer.Serialize(loginview); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://localhost:44374/api/adcxx/ValidateUser"); request.Content = content; var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { // 读取响应文本内容 var responseContent = await response.Content.ReadAsStringAsync(); // 反序列化为定义好的模型对象 var loginResponse = JsonSerializer.Deserialize<ApiLoginResponse>(responseContent); // 验证API返回的成功条件 if (loginResponse != null && loginResponse.message == "success" && loginResponse.status) { // 提取用户核心信息 string userId = loginResponse.data.userID; string userName = loginResponse.data.userName; string userRole = loginResponse.data.userRole; string environment = loginResponse.data.environment; // 此处可添加后续逻辑,比如存储用户信息到Session、跳转至首页等 } else { // 处理登录验证失败场景,比如提示用户账号密码错误 } } else { // 处理API请求失败场景,比如网络错误、服务端异常 } }
额外提示
- 确保代码引用了
System.Text.Json命名空间,这是.NET内置的序列化工具。 - 如果遇到JSON键名与模型属性大小写不匹配的问题,可配置序列化选项忽略大小写:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var loginResponse = JsonSerializer.Deserialize<ApiLoginResponse>(responseContent, options);
内容的提问来源于stack exchange,提问作者ahmed abdelaziz
相关产品推荐
相关产品推荐

