2014-03-13 342 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) 
相關問題