带Cognito认证的AWS API Gateway Lambda函数返回415错误,ContentType异常
解决配置Cognito认证的API Gateway Lambda返回415 Unsupported Media Type错误
这个问题我之前也遇到过几次,核心就是请求的Content-Type被莫名改成了text/plain,导致你的ASP.NET Core后端因为不支持这个媒体类型返回415错误。结合Cognito+API Gateway的场景,咱们一步步来排查解决:
一、先定位问题根源
从你提供的WebHost日志可以明确:原始请求的Content-Type: application/json在到达后端前被改成了text/plain,而ASP.NET Core默认只处理application/json类型的请求体,因此触发了415错误。问题大概率出在API Gateway的请求转发或Cognito认证后的请求处理环节。
二、针对性解决方案
1. 检查API Gateway集成配置
如果你用的是Lambda代理集成
代理集成理论上会原样传递请求Headers,但可能存在以下配置问题:
- 检查API Gateway阶段设置:进入你的API Gateway -> 对应阶段 ->
Settings-> 查看Request Headers是否有强制修改Content-Type的规则,如果有,删除该规则。 - 检查Method Request配置:进入对应API方法 ->
Method Request->HTTP Request Headers,确认Content-Type是作为Required或Optional存在,没有被错误的默认值覆盖。
如果你用的是非Lambda代理集成
非代理集成需要手动配置请求模板,很可能是这里的配置导致Content-Type被篡改:
- 进入对应API方法 ->
Integration Request->Request Templates:- 确保存在
application/json的模板,内容设置为$input.json('$')(原样传递JSON请求体),并且模板关联的Content-Type是application/json。 - 检查
Passthrough Behavior设置,建议设为WHEN_NO_MATCH,避免无匹配模板时强制修改请求类型。
- 确保存在
- 查看
Integration Request的Headers配置:确认没有手动设置Content-Type为text/plain,如果有,移除该配置,让请求头从前端原样传递。
2. 排查自定义Lambda授权者(如果使用了)
如果你的Cognito认证用了自定义Lambda授权者,检查授权者代码是否有修改请求Headers的逻辑——有些开发者会在授权过程中误改Content-Type,导致后续请求类型异常。
3. 临时兼容方案:让ASP.NET Core支持text/plain请求体
如果暂时找不到API Gateway篡改Content-Type的原因,可以让你的ASP.NET Core后端兼容text/plain类型的JSON请求体,避免415错误。在Program.cs(.NET 6+)或Startup.cs中添加以下配置:
builder.Services.AddControllers(options => { // 插入自定义的text/plain输入格式化器 options.InputFormatters.Insert(0, new TextPlainInputFormatter()); }); // 定义text/plain输入格式化器 public class TextPlainInputFormatter : TextInputFormatter { public TextPlainInputFormatter() { SupportedMediaTypes.Add("text/plain"); SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); } protected override bool CanReadType(Type type) { // 支持字符串或自定义类的反序列化 return typeof(string) == type || type.IsClass; } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { using var reader = new StreamReader(context.HttpContext.Request.Body, encoding); var content = await reader.ReadToEndAsync(); if (typeof(string) == context.ModelType) { return await InputFormatterResult.SuccessAsync(content); } // 尝试将text/plain内容反序列化为JSON对象 try { var model = JsonSerializer.Deserialize(content, context.ModelType); return await InputFormatterResult.SuccessAsync(model); } catch { return await InputFormatterResult.FailureAsync(); } } }
三、额外排查步骤
- 打印Lambda输入Event:在Lambda代码中添加日志,打印收到的完整Event对象,查看其中的
headers.Content-Type值,确认是API Gateway传递过来的就是text/plain,还是ASP.NET Core运行时解析的问题。 - 直接测试Lambda:绕过API Gateway,用Lambda测试事件模拟
Content-Type: application/json的请求,看后端是否正常响应,以此确认问题是否出在API Gateway环节。
内容的提问来源于stack exchange,提问作者Dar
相关产品推荐
相关产品推荐

