我正在使用Web API创建Web服务。我实现了一个简单的类
public class ActivityResult
{
public String code;
public int indexValue;
public int primaryCodeReference;
}
然后我在我的控制器中实现了
[HttpPost]
public HttpResponseMessage Post(ActivityResult ar)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
但是当我调用API传递POST文件时json:
{"code":"XXX-542","indexValue":"3","primaryCodeReference":"7"}
我收到以下错误消息:
{
"Message": "The request entity's media type 'text/plain' is not supported for this resource.",
"ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'ActivityResult' from content with media type 'text/plain'.",
"ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
"StackTrace": " in System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n in System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n in System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}
我做错了什么?
答案 0 :(得分:177)
在HTTP请求中,您需要将Content-Type设置为:Content-Type: application/json
因此,如果您正在使用fiddler客户端将Content-Type: application/json
添加到请求标头
答案 1 :(得分:1)
另一个提示...将“content-type:application / json”...添加到Composer / Parsed选项卡上的文本框字段。那里已经填充了3行,所以我将这个Content-type添加为第4行。这使得邮政工作。
答案 2 :(得分:1)
Content-Type:application/json
定义任何应注释为[FromBody]
的POST请求方法输入参数时,例如:
[HttpPost]
public HttpResponseMessage Post([FromBody]ActivityResult ar)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
任何JSON输入数据都必须是原始数据。
答案 3 :(得分:0)
我在接受的答案中涵盖了所有设置。 我遇到的问题是我试图更新实体框架实体类型"任务"像:
public IHttpActionResult Post(Task task)
对我有用的是创建我自己的实体" DTOTask"像:
public IHttpActionResult Post(DTOTask task)
答案 4 :(得分:0)
如果没有提及任何内容,则需要在web api请求标头部分中包含 <a href="{{ route('products.destroy', $product->slug) }}" class="btn btn-danger btn-xs" onclick="event.preventDefault();document.getElementById('delete-product-{{$product->slug}}').submit();">Delete</a>
<form id="delete-product-{{$product->slug}}" method="POST" action="{{ route('products.destroy', $product->slug) }}" style="display: none;">
@csrf
@method('DELETE')
</form>
,然后默认情况下Content-Type:application/json
会传递给请求。
在postman工具上测试api的最佳方法。