You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Lambda API可接收Postman的POST请求体,Angular前端请求体为空

问题排查与解决方案

核心现象

  • .NET Lambda API的POST请求在Postman调用时正常接收请求体,但Github Pages部署的Angular应用调用时,请求体字段为空(CloudWatch日志显示UserName/Password为空)
  • GET请求正常,无CORS错误,Angular拦截器确认请求体已正确填充

可能原因及对应解决方案

1. API Gateway集成模式问题(最常见)

如果你的API Gateway使用了Lambda Proxy集成,.NET Core的模型绑定无法自动解析请求体——因为Proxy模式下,请求的原始数据会封装在Lambda的event对象中,而非直接传递给Controller参数。

解决方法:
修改Controller方法,手动读取并反序列化请求体:

[HttpPost(Name = "Login")]
public async Task<ActionResult<string>> IssueJWTAsync()
{
    using var reader = new StreamReader(Request.Body);
    var requestBody = await reader.ReadToEndAsync();
    var userInputDTO = JsonSerializer.Deserialize<UserInputDTO>(requestBody);

    LambdaLogger.Log(userInputDTO?.UserName ?? "未获取到用户名");
    LambdaLogger.Log(userInputDTO?.Password ?? "未获取到密码");
    
    if (userInputDTO == null || string.IsNullOrEmpty(userInputDTO.UserName) || string.IsNullOrEmpty(userInputDTO.Password))
    {
        return StatusCode(400, "请求体格式错误");
    }

    string? jwt = await _userCommandRepository.Login(userInputDTO.UserName, userInputDTO.Password);
    return jwt == null ? StatusCode(401) : Ok(jwt);
}

或者,将API Gateway的集成模式改为非Proxy的Lambda集成,并配置请求体到Lambda参数的映射(需在API Gateway控制台调整集成请求设置)。

2. DTO模型绑定要求未满足

.NET Core模型绑定需要DTO类满足以下条件:

  • 拥有公共无参构造函数
  • 属性为公共可读写(get; set;)

检查UserInputDTO定义,确保符合要求:

public class UserInputDTO
{
    public string UserName { get; set; }
    public string Password { get; set; }

    // 必须有无参构造函数
    public UserInputDTO() {}
}

3. 请求Content-Type验证

Angular的HttpClient.post默认会发送Content-Type: application/json,但需确认:

  • 前端拦截器未修改该请求头
  • API Gateway的CORS配置中,Allowed Headers包含Content-Type
  • API Gateway的集成请求未限制Content-Type

4. 前端responseType设置影响(次要排查)

前端代码中{responseType: 'text' as 'json'}是处理响应的设置,但如果后端返回的是JSON格式字符串,可能导致解析异常。可尝试调整:

public loginRequest(userInfo: UserRequest): Observable<string> {
    return this.http.post<string>(routeCreator("Session"), userInfo)
        .pipe(
            catchError(errorHandler)
        );
}

若后端返回纯文本JWT,再添加responseType配置:

{responseType: 'text' as const}

内容的提问来源于stack exchange,提问作者Pap113

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:52:10