使用PostMan Rest Client创建用户时遇不支持媒体类型错误求助
解决PostMan调用Web API创建用户时的UnsupportedMediaTypeException错误
我用PostMan Rest Client调用Web API创建新用户时,收到了如下错误:
{ "message": "请求实体的媒体类型'text/plain'对此资源不支持。", "exceptionMessage": "没有MediaTypeFormatter可从媒体类型为'text/plain'的内容中读取'CustomerDto'类型的对象。", "exceptionType": "System.Net.Http.UnsupportedMediaTypeException", "stackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" }
我的ApiController代码如下:
[HttpPost] public IHttpActionResult CreateCustomer(CustomerDto customerDto) { if (!ModelState.IsValid) return BadRequest(); var customer = Mapper.Map<CustomerDto, Customer>(customerDto); _context.Customers.Add(customer); _context.SaveChanges(); customerDto.Id=customer.Id; return Created(new Uri(Request.RequestUri + "/" + customer.Id), customerDto); }
问题原因
这个错误的核心是:你的Web API默认期望接收JSON格式的请求体,ASP.NET Web API会用JsonMediaTypeFormatter解析复杂类型参数,但PostMan发送的请求媒体类型是text/plain,API找不到对应的格式化器把纯文本转换成CustomerDto对象,因此抛出了这个异常。
解决步骤
设置正确的请求头
打开PostMan的请求窗口,切换到Headers标签,添加一条请求头:- 键:
Content-Type - 值:
application/json
- 键:
确保请求体是合法JSON
切换到Body标签:- 选择
raw选项 - 在右侧的格式下拉框里选择
JSON(不要选Text) - 输入符合
CustomerDto结构的JSON内容,比如:{ "name": "张三", "email": "zhangsan@example.com", // 其他你的CustomerDto需要的字段 }
- 选择
(可选)确认API的JSON格式化配置
如果上面两步做完还是有问题,可以检查你的WebApiConfig.cs里是否启用了JSON格式化(一般默认是开启的),确保有类似代码:public static void Register(HttpConfiguration config) { // 其他配置... config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); }
这样调整后,PostMan发送的请求就会以JSON格式被API正确解析,就能成功创建用户了。
内容的提问来源于stack exchange,提问作者user12930398
相关产品推荐
相关产品推荐

