我正在使用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)"
}
我在做什麼錯?
您必須添加一個「application/json」的頭部,以便從客戶端接受有效內容。 –
我已經在我的HTTP請求中正確設置了標頭。然而,這個問題似乎是服務器端:https://www.dropbox.com/s/xlidnnybs8v6d0u/Cattura.JPG – GVillani82
它看起來像只設置'Accept'頭到'application/json'。您還需要將「Content-Type」頭設置爲「application/json」。 –