.NET 6.0接口如何接收Content-Type为application/jwt的POST请求?
解决.NET 6 API识别application/jwt类型请求的问题
你的问题核心是.NET Core默认的JSON输入格式化器不支持application/jwt这个Content-Type,导致请求被拒绝返回415错误。以下是两种可行的解决方案:
方案1:扩展默认JSON输入格式化器
直接给现有的SystemTextJsonInputFormatter添加application/jwt媒体类型支持,这样它就能处理该类型的请求(因为Glassfy的请求体本质是JSON格式)。
在Program.cs中修改服务配置:
builder.Services.AddControllers(options => { // 获取默认的JSON输入格式化器 var jsonFormatter = options.InputFormatters .OfType<SystemTextJsonInputFormatter>() .FirstOrDefault(); if (jsonFormatter != null) { // 添加application/jwt到支持的媒体类型列表 jsonFormatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/jwt")); } });
方案2:自定义输入格式化器
如果需要更明确的处理逻辑,可以单独定义一个针对application/jwt的格式化器:
首先创建格式化器类:
public class JwtInputFormatter : SystemTextJsonInputFormatter { public JwtInputFormatter(JsonOptions options) : base(options) { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/jwt")); } }
然后在Program.cs中注册这个格式化器:
builder.Services.AddControllers(options => { var jsonOptions = builder.Services.BuildServiceProvider() .GetRequiredService<IOptions<JsonOptions>>().Value; // 将自定义格式化器插入到列表最前面,确保优先处理 options.InputFormatters.Insert(0, new JwtInputFormatter(jsonOptions)); });
备选方案:手动读取请求体
如果不想修改全局配置,可以直接在控制器方法中手动读取请求体内容,再自行解析模型:
[HttpPost("ReceiveWebHook")] public async Task<ActionResult> ReceiveWebHook() { // 读取请求体中的JWT字符串 var jwtContent = await new StreamReader(Request.Body).ReadToEndAsync(); // 解析为GlassfyWebHookRequest模型 var req = JsonSerializer.Deserialize<GlassfyWebHookRequest>(jwtContent); // 后续业务逻辑处理 return Ok(); }
验证
修改完成后重启API,用Postman设置Content-Type为application/jwt测试,请求应该能正常返回200 OK,模型绑定也能正常工作。
内容的提问来源于stack exchange,提问作者Dan Chase
相关产品推荐
相关产品推荐

