I have a class that name is Advertisement:
public class Advertisement
{
public string Title { get; set; }
public string Desc { get; set; }
}
"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.
In your WebApiConfig.cs
add this inside of register
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
Several issues:
application/octet-stream
, use application/json;charset=UTF-8
, instead. public IHttpActionResult Test(Advertisement advertisement)
needs to have [FromBody]
in it:
public IHttpActionResult Test([FromBody]Advertisement advertisement) { ... }
By default, the ApiController expects anything being passed in to represent URL parameters, so you'd need that [FromBody]
for any data you are posting in the Request Body that you want parsed out.
You need to decorate your Post method with [System.Web.Http.HttpPost]
so that it doesn't think it's the MVC version [System.Web.Mvc.HttpPost]
. Ensure you put the full thing, because [HttpPost]
will also default to the MVC version. It's probably not a bad idea to rename Test
to Post
, as well, though you might be using that for a Unit Test method, so not sure on that one.
Send your data as JSON: { Title: "some title", Desc: "some description" }
Do something with advertisement
inside your Post()
function:
string title = advertisement.Title;
string desc = advertisement.Desc;