Angular向ASP.NET Web API传递登录模型数据失败问题求助
Angular前端向ASP.NET API后端传递LoginForm模型为空的问题
搭建Angular前端到ASP.NET API后端的登录功能时,前端传递包含邮箱和密码的LoginForm模型,前后端字段命名完全一致,但后端接收的LoginForm实例为空,请求能正常到达后端。
ASP.NET后端代码
登录端点
[Route("/[controller]/Login")] [HttpPost] public async Task<IActionResult> Login(LoginForm loginForm)
LoginForm模型类
public class LoginForm { [Required] public string Email { get; set; } [Required] public string Password { get; set; } }
Angular前端代码
登录请求方法
login(model: LoginForm) { console.log(model); return this.http.post(this.authUrl + "Login", model, {}).pipe( map((response: any) => { const user = response; if (user.result.accountID > 0) { localStorage.setItem("token", user.token); this.decodedToken = this.helper.decodeToken(user.token); } }) ); }
LoginForm接口
export interface LoginForm { Email: string; Password: string; }
测试验证信息
- 前端控制台日志:
{Email: 'test', Password: 'test'} - 请求负载内容:
{Email: "test", Password: "test"} - 后端接收状态:LoginForm实例的Email和Password字段均为null
解决方法
核心原因
ASP.NET默认会从URL查询参数或表单数据中绑定简单参数,而Angular的HttpClient.post默认发送JSON格式的请求体,后端未明确指定从请求体绑定数据,导致无法解析模型。
修复步骤
后端添加[FromBody]特性
在Login方法的参数上添加[FromBody],明确告知ASP.NET从请求体(JSON)中绑定模型数据:public async Task<IActionResult> Login([FromBody] LoginForm loginForm)确认前端请求头(可选)
Angular的HttpClient默认会设置Content-Type: application/json,如果手动修改过请求头,确保不要使用application/x-www-form-urlencoded这类不匹配的格式。若需显式指定,可添加请求选项:import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; // 在post请求中传入httpOptions return this.http.post(this.authUrl + "Login", model, httpOptions).pipe(...);检查模型属性配置
确保后端LoginForm类的属性为public(代码已满足),且具备公共的getter/setter(自动属性默认包含)。
内容的提问来源于stack exchange,提问作者Bart
相关产品推荐
相关产品推荐

