Vue前端调用接口返回406 Not Acceptable且请求未达后端如何解决?
问题根因
406 Not Acceptable错误结合请求未命中后端端点的问题,由以下3个错误共同导致:
- 后端复杂类型查询参数未指定
[FromQuery],ASP.NET Core默认尝试从GET请求不存在的Body中绑定参数,路由匹配失败 - 前端参数序列化错误,实际传值为
ContentType.Pdf字符串,无法匹配后端枚举ContentType的合法值 - 前端请求未指定
Accept头,与后端[Produces]限定的返回格式不匹配
修复步骤
1. 修复后端参数绑定
给GET接口的复杂类型参数添加[FromQuery]注解,指定从查询参数绑定模型:
public async Task<FileContentResult> GetContractAgreementAsync([FromRoute] string id, [FromQuery] GetOverdraftContractAgreementRequest request)
2. 修复前端传值错误
检查前端参数传值逻辑,确保查询参数ContentType的值为Pdf而非ContentType.Pdf,示例正确写法:
// 假设前端定义了枚举映射 const ContentTypeEnum = { Html: 'Html', Pdf: 'Pdf' } const getContractAgreement = async (id) => { const response = await httpClient.get(`api/credit-products/overdrafts/${id}/contract-agreement`, { params: { ContentType: ContentTypeEnum.Pdf }, // 新增Accept头匹配后端返回格式 headers: { 'Accept': 'application/pdf' } }) return response.data }
3. (可选)配置后端枚举字符串序列化
如果仍存在枚举绑定失败问题,在Program.cs中添加枚举字符串转换器,兼容字符串格式的枚举参数:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); });
内容的提问来源于stack exchange,提问作者grozdeto
相关产品推荐
相关产品推荐

