没有媒体类型格式化程序可用于读取 asp.net Web API 中的 'Advertisement' 类型的对象



我有一个名为advertising的类:

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

但是当我用Postman测试它时,我遇到了这个错误,

 "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)rn   at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)rn   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"

有人能帮我吗?

在您的WebApiConfig.cs中添加此寄存器

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

"ExceptionMessage": "No MediaTypeFormatter is available to read type of ' advertising '从媒体类型为'application/octet-stream'的内容中读取类型为' advertising '的对象",

这意味着您的应用程序无法读取请求提供的八字节流内容类型。这是我在使用Web API时遇到的一个挫折。然而,有一种方法可以绕过它。简单的方法是将Content-type修改为"application/json"或"application/xml",这样更容易阅读。比较困难的方法是提供您自己的MediaTypeFormatter。

几个问题:

  1. application/json;charset=UTF-8代替application/octet-stream
  2. public IHttpActionResult Test(Advertisement advertisement)需要[FromBody]在里面:

    public IHttpActionResult Test([FromBody]Advertisement advertisement) { ... }

    默认情况下,ApiController期望传入的任何内容都代表URL参数,因此您需要[FromBody]来表示您想要解析出的任何在Request Body中发布的数据。

  3. 你需要用[System.Web.Http.HttpPost]装饰你的Post方法,这样它就不会认为它是MVC版本的[System.Web.Mvc.HttpPost]。确保你把完整的东西,因为[HttpPost]也将默认为MVC版本。将Test重命名为Post也可能不是一个坏主意,尽管您可能将其用于单元测试方法,所以不确定。

  4. 发送数据为JSON: { Title: "some title", Desc: "some description" }

  5. Post()函数中使用advertisement:

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

相关内容

  • 没有找到相关文章

最新更新