2014-03-13 320 views
77

我正在使用Web API创建Web服务。我实现了一个简单的类将POST中的json发送到Web API服务时出错

public class ActivityResult 
{ 
    public String code; 
    public int indexValue; 
    public int primaryCodeReference; 
} 

然后,我有我的控制器

[HttpPost] 
public HttpResponseMessage Post(ActivityResult ar) 
{ 
    return new HttpResponseMessage(HttpStatusCode.OK); 
} 

内部实现但当我称之为POST传递文件JSON的API:

{"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)" 
} 

我在做什么错?

+8

您必须添加一个“application/json”的头部,以便从客户端接受有效内容。 –

+0

我已经在我的HTTP请求中正确设置了标头。然而,这个问题似乎是服务器端:https://www.dropbox.com/s/xlidnnybs8v6d0u/Cattura.JPG – GVillani82

+4

它看起来像只设置'Accept'头到'application/json'。您还需要将“Content-Type”头设置为“application/json”。 –

回答

155

在您需要的内容类型设置为HTTP请求:如果您使用招客户端添加到Content-Type: application/json请求头

1

另一个秘诀......在哪里添加Content-Type: application/json

因此,“内容-type:application/json“...复制到Composer/Parsed选项卡上的文本框。这里已经有3条线了,所以我把这个Content-type添加为第4条线。这使邮报工作。

0

请检查您是否在传递方法为POST而不是GET。 如果是这样,你会得到同样的错误,因为你张贴在上面。

$http({    
method: 'GET', 

请求实体的媒体类型 'text/plain的' 不支持 该资源。

+1

这个问题具体是关于一个http POST,他没有向服务器发送数据的服务器请求数据。 – War

0

我已将我的所有设置都包含在接受的答案中。 我的问题是,我试图更新像实体框架实体类型“任务”:

public IHttpActionResult Post(Task task) 

什么工作对我来说是创造我自己的实体“DTOTask”,如:

public IHttpActionResult Post(DTOTask task) 
相关问题