C#发送POST请求时如何使用JsonProperty指定名称构造JSON负载
问题定位与修复方案
核心根因
当前代码触发422错误的问题点如下:
- 构造请求负载时直接调用
userRequest.ToString(),该方法是对象的默认实例方法,不会执行任何JSON序列化逻辑:既不会识别属性上标注的[JsonProperty]特性,也不会自动把类属性转换为JSON键值对,对自定义类来说默认仅返回类名称字符串,和预期的JSON负载完全无关。 UserRequest类存在编译级错误:构造函数的布尔参数名为sysadmin,但赋值时引用了不存在的变量isAdmin,代码无法正常编译运行。- 复用的
HttpClient全局header存在状态污染问题:每次调用方法都往client.DefaultRequestHeaders中新增Accept、Authorization头,多次调用时会因重复header触发运行时异常。
具体修复步骤
- 替换无效的
userRequest.ToString()逻辑,使用项目已引入的Newtonsoft.Json序列化方法处理请求对象,序列化过程会自动识别[JsonProperty]特性配置,输出指定的小写键名JSON:// 序列化请求对象,自动应用JsonProperty标注的配置 string jsonPayload = JsonConvert.SerializeObject(userRequest); req.Content = new StringContent( jsonPayload, Encoding.UTF8, "application/json" ); - 修正
UserRequest类的构造函数参数匹配错误:public class UserRequest { [JsonProperty(PropertyName = "email")] public string Email { get; set; } [JsonProperty(PropertyName = "isadmin")] public bool IsAdmin{ get; set; } [JsonProperty(PropertyName = "password")] public string Password { get; set; } public UserRequest(string email, bool sysadmin, string password) { Email = email; // 修正变量名匹配,解决编译报错问题 IsAdmin = sysadmin; Password = password; } } - 调整header的设置位置,将请求级别的header挂载到当前
HttpRequestMessage实例上,避免修改HttpClient的全局默认状态:var req = new HttpRequestMessage(HttpMethod.Post, url); // 请求专属header,不会污染全局client的配置 req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
调整完成后,序列化输出的JSON负载会与后端要求的格式完全匹配:
{ "email": "myMail@mail.com", "password": "passwd", "isadmin": true }
内容的提问来源于stack exchange,提问作者davidvera
相关产品推荐
相关产品推荐

