c# – 将POST中的json发送到Web API服务时出错
c# – 将POST中的json发送到Web API服务时出错
问题:
我正在使用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)"
}
我究竟做错了什么?
I’m creating a web service using Web API.I implemented a simple classAnd then I have implemented inside my controllerBut when I call the API passing in POST the file json:I obtain the following error message:What am I doing wrong?
解决方案:
方案1:
在HTTP请求中,您需要将Content-Type设置为: Content-Type: application/json
因此,如果您正在使用fiddler客户端,请将Content-Type: application/json
到请求标头中
方案2:
另一个提示…将“content-type:application / json”…添加到Composer / Parsed选项卡上的文本框字段。 那里已经填充了3行,所以我将这个Content-type添加为第4行。 这使邮政工作。
方案3:
- 您必须添加标题属性
Content-Type:application/json
定义任何应该注释为
[FromBody]
POST请求方法输入参数时, 例如 :[HttpPost] public HttpResponseMessage Post([FromBody]ActivityResult ar) { return new HttpResponseMessage(HttpStatusCode.OK); }
任何JSON输入数据都必须是原始数据。
方案4:
请检查您是否正在将方法作为POST
传递而不是GET
。 如果是这样,你将得到与上面发布的相同的错误。
$http({
method: 'GET',
此资源不支持请求实体的媒体类型“text / plain”。
方案5:
我在接受的答案中涵盖了所有设置。 我遇到的问题是我试图更新实体框架实体类型“任务”,如:
public IHttpActionResult Post(Task task)
对我有用的是创建我自己的实体“DTOTask”,如:
public IHttpActionResult Post(DTOTask task)
方案6:
当不提及任何内容时,它需要在web api请求标题部分中包含Content-Type:application/json
,然后默认情况下它是Content-Type:text/plain
传递给请求。
在postman工具上测试api的最佳方法。