C# API客户端认证时用户名密码传入控制器为空问题求助
问题根源
核心问题是客户端请求的内容格式与控制器期望的不匹配,导致模型绑定失败,最终AuthenticationRequestBody参数为null:
- 控制器通过
[FromBody]期望接收JSON格式的请求体,结构需要包含UserName和Password字段 - 你错误地将
FormUrlEncodedContent对象直接序列化为JSON发送,而FormUrlEncodedContent是用于表单提交的类型,其序列化后的JSON结构完全不符合控制器的要求
解决方案
修改客户端代码,直接构造符合控制器接收格式的对象,再序列化为JSON发送:
public async Task<AuthenticatedUser> Authenticate(string username, string password) { // 构造与控制器AuthenticationRequestBody匹配的对象 var requestBody = new { UserName = username, Password = password, grant_type = "password" // 若控制器不需要该字段,可直接移除 }; using (HttpResponseMessage response = await _httpClient.PostAsync( "http://localhost:5063/api/authentication/authenticate", new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json"))) { if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync<AuthenticatedUser>(); return result; } else { throw new Exception(response.ReasonPhrase); } } }
额外说明
- 确保JSON键名与
AuthenticationRequestBody类的属性名完全匹配(大小写敏感,比如UserName不能写成username) - 若认证逻辑不需要
grant_type字段,可直接从请求体中移除该参数 - 调试时可先用接口测试工具验证控制器接口本身的可用性,再排查客户端代码问题
内容的提问来源于stack exchange,提问作者Franko
相关产品推荐
相关产品推荐

