创建Controller调用HttpPost时遭遇415 Unsupported Media Type错误求助
HTTP 415 Unsupported Media Type 错误排查与解决
我正尝试创建一个Controller,用于将类实例添加至SQL数据库,但调用HttpPost接口时持续出现HTTP 415错误,错误详情如下:
Unhandled exception rendering component: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"00-f30954ed2136f9135eeb829d54578d45-69a58efb9fadfcc2-00"} at blazorTestApp.Client.Repositories.AuthorsRepo.AddAuthor(Authors Author) at blazorTestApp.Client.Pages.Authors.AddAuthor.OnSubmit() at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync() at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
Controller代码
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using blazorTestApp.Shared.Entities; using Microsoft.AspNetCore.Mvc; namespace blazorTestApp.Server.Controllers { [ApiController] [Route("api/[controller]")] public class AuthorsController : ControllerBase { private readonly Database DB; public AuthorsController(Database DB) { this.DB = DB; } [HttpPost] public async Task<ActionResult<int>> Post(Authors Author) { DB.Add(Author); await DB.SaveChangesAsync(); return Ok(); } } }
Http服务文件
namespace blazorTestApp.Client.Classes_FE { public class HttpService : IHttpService { private readonly HttpClient httpClient; public HttpService(HttpClient httpClient) { this.httpClient = httpClient; } public async Task<HttpResponse<object>> POST<T>(string url, T data) { var JsonData = JsonSerializer.Serialize(data); var StringContent = new StringContent(JsonData, Encoding.UTF8, "applicaiton/json"); var ResponseMessage = await httpClient.PostAsync(url, StringContent); return new HttpResponse<object>(null, ResponseMessage, ResponseMessage.IsSuccessStatusCode); } } }
该文件继承自仅包含上述POST方法的接口,该接口已注入至仓储类中。
发起Http请求的仓储类
namespace blazorTestApp.Client.Repositories { public class AuthorsRepo { private IHttpService httpService; private string url = "api/Authors"; public AuthorsRepo(IHttpService httpService) { this.httpService = httpService; } public async Task AddAuthor(Authors Author) { var response = await httpService.POST(url, Author); if(!response.Success) { throw new ApplicationException(await response.GetBodyString()); } } } }
调用AddAuthor方法的页面文件
@page "/Authors/Add" @inject AuthorsRepo authorRepo @inject NavigationManager NavMan @code { public Authors Author {get; set;} = new Authors(); public async Task OnSubmit() { //Unrelated code await authorRepo.AddAuthor(Author); NavMan.NavigateTo("Authors"); } }
问题原因与修复方案
HTTP 415错误的核心原因是请求的Content-Type拼写错误:
在HttpService的POST方法中,你将application/json误写为applicaiton/json(缺少一个字母o),导致服务器无法识别请求的媒体类型。
1. 核心修复
修正Content-Type的拼写错误:
var StringContent = new StringContent(JsonData, Encoding.UTF8, "application/json");
2. 额外优化建议
- 为Controller的Post方法添加
[FromBody]特性,明确指定从请求体绑定参数,避免潜在的参数绑定问题:[HttpPost] public async Task<ActionResult<int>> Post([FromBody] Authors Author) { DB.Add(Author); await DB.SaveChangesAsync(); return Ok(); } - 使用
HttpClient.PostAsJsonAsync简化代码,该方法会自动完成序列化并设置正确的Content-Type,无需手动创建StringContent:public async Task<HttpResponse<object>> POST<T>(string url, T data) { var ResponseMessage = await httpClient.PostAsJsonAsync(url, data); return new HttpResponse<object>(null, ResponseMessage, ResponseMessage.IsSuccessStatusCode); }
内容的提问来源于stack exchange,提问作者Saucter
相关产品推荐
相关产品推荐

