C# ASP.NET Core Web API POST请求遇415 UnsupportedMediaType错误排查
问题:POST请求返回415 UnsupportedMediaType错误原因分析
场景说明
在HomeController中实现ApiTester方法,加载该页面时会向AuthController的ApiTest接口发起POST请求,首页跳转链接如下:
<a href="@Url.Action("ApiTester", "Home")">ApiTester Click Here</a>
HomeController代码
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System.Diagnostics; using System.Net.Http.Headers; using System.Text; using TestWebApplication.Models; namespace TestWebApplication.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [HttpGet] public async Task<IActionResult> ApiTester() { var client = new HttpClient(); var values = new Dictionary<string, string> { { "Name", "Alice" } }; var content = new FormUrlEncodedContent(values); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var response = await client.PostAsync("https://localhost:7284/api/Auth/ApiTest", content); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); ViewBag.ApiResponse = result; } else { ViewBag.ApiResponse = "Error: " + response.StatusCode; } return View(); } } }
AuthController代码
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; namespace TestWebApplication.Controllers { [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { [HttpGet("GetTest")] public IActionResult GetTest() { return Ok(new { message = "Get Test Succesfull!" }); } [HttpPost("ApiTest")] public IActionResult ApiTest([FromBody] Dictionary<string, string> values) { string name = values["name"]; return Ok(new { message = "200: Post Test Succesfull!" }); } } }
Program.cs代码
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
问题
当前请求返回Error: UnsupportedMediaType(状态码415),但移除ApiTest方法的[FromBody]参数后请求可正常执行,请问该错误的原因是什么?
错误原因
请求格式与接口接收规则不匹配
- 客户端发送的是
application/x-www-form-urlencoded格式的表单数据,对应Content-Type头也是该类型。 - 但服务端的ApiTest方法用
[FromBody]标记参数,这个特性专门用于接收JSON/XML格式的请求体(Content-Type通常为application/json),无法处理表单格式的数据。
- 客户端发送的是
ASP.NET Core参数绑定机制限制
- 当使用
[FromBody]时,ASP.NET Core会调用JSON格式化器去解析请求体,但你的请求是表单格式,没有对应的格式化器能处理,因此返回415错误。 - 移除
[FromBody]后,ASP.NET Core会自动从表单数据中绑定参数,所以请求能正常执行。
- 当使用
内容的提问来源于stack exchange,提问作者Waller
相关产品推荐
相关产品推荐

