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

前端 未结 3 962
悲哀的现实
悲哀的现实 2021-02-18 18:13

I have a class that name is Advertisement:

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


        
3条回答
  •  悲哀的现实
    2021-02-18 18:40

    Several issues:

    1. Instead of posting it as application/octet-stream, use application/json;charset=UTF-8, instead.
    2. 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.

    3. 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.

    4. Send your data as JSON: { Title: "some title", Desc: "some description" }

    5. Do something with advertisement inside your Post() function:

      string title = advertisement.Title; string desc = advertisement.Desc;

提交回复
热议问题