Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No MediaTypeFormatter is available to read an object of type 'Advertisement' in asp.net web api

Tags:

I have a class that name is Advertisement:

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

and in my controller:

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());
    }

but when I test it with Postman I face this error,

 "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 help me?

like image 954
Mehran Ahmadi Avatar asked May 30 '15 08:05

Mehran Ahmadi


2 Answers

In your WebApiConfig.cs add this inside of register

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
like image 192
Louie Almeda Avatar answered Sep 23 '22 22:09

Louie Almeda


"ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Advertisement' from content with media type 'application/octet-stream'.",

That means that your application cannot read octet-stream Content-Type - which is what the request provided. This is one frustration I have with Web API. However there is a way around it. The easy way is to modify the Content-type to 'application/json' or 'application/xml' which is easily read. The harder way is to provide your own MediaTypeFormatter.

like image 24
Dave Agaba Avatar answered Sep 19 '22 22:09

Dave Agaba