2015-05-30 39 views
11

我有一個類,名字是廣告:沒有MediaTypeFormatter可讀取類型的對象「廣告」在asp.net網頁API

public class Advertisement 
{ 
    public string Title { get; set; } 
    public string Desc { get; set; } 
} 

,並在我的控制器:

public class OrderController : ApiController 
{ 
    public UserManager<IdentityUser> UserManager { get; private set; } 

    // Post api/Order/Test 

    [Route("Test")] 
    public IHttpActionResult Test(Advertisement advertisement) 
    { 
     var currentUser = User.Identity.GetUserId(); 
     Task<IdentityUser> user = UserManager.FindByIdAsync(currentUser); 

     return Ok(User.Identity.GetUserId()); 
    } 

但是當我用郵差測試它時,我面對這個錯誤,

"Message": "The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.", 
"ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Advertisement' from content with media type 'application/octet-stream'.", 
"ExceptionType": "System.Net.Http.UnsupportedMediaTypeException", 
"StackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" 

Can AnyBody能幫助我嗎?

+0

內部從我出現的錯誤,你有沒有Content-Type頭?在Postman調用中添加適當的頭文件Content-Type,並且應該修復它。 –

+0

我有'Content-Type'和'Accept'在我的頭文件中@DaveAgaba –

+0

請查看下面的答案。 –

回答

2

「ExceptionMessage」:「沒有MediaTypeFormatter可從與媒體類型‘應用程序/八位字節流’內容閱讀類型的對象‘廣告’」,

這意味着,您的應用程序無法讀取octet-stream Content-Type - 這是請求提供的內容。這是我對Web API的一個挫折。但是有一種解決方法。簡單的方法是將Content-type修改爲'application/json'或'application/xml',這很容易閱讀。 更難的方法是提供您自己的MediaTypeFormatter。

+0

'這個'教程鏈接現已停止。 – NStuke

25

在你WebApiConfig.cs添加此寄存器

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream")); 
+0

這不起作用。 config.Formatters.JsonFormatter.CanWriteType(typeof(MyModel));返回false。 – JDC

相關問題