我有一个名称为Advertisement的类:
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)\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)"AnyBody能帮我吗?
发布于 2016-05-27 16:07:52
在您的WebApiConfig.cs中,将以下内容添加到寄存器中
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));发布于 2015-05-30 17:22:31
"ExceptionMessage":“没有应用程序可用于从媒体类型为‘MediaTypeFormatter /octet-stream’的内容中读取类型为'Advertisement‘的对象。”,
这意味着您的应用程序不能读取八位字节-流内容-类型-这是请求提供的内容。这是我对Web API的一个挫败感。然而,有一种方法可以绕过它。最简单的方法是将Content-type修改为“application/json”或“application/xml”,这样更容易阅读。更难的方法是提供您自己的MediaTypeFormatter。
发布于 2018-04-06 10:05:00
几个问题:
application/octet-stream的形式发布,而是使用application/json;charset=UTF-8。public IHttpActionResult Test(Advertisement advertisement)需要包含[FromBody]:public IHttpActionResult Test([FromBody]Advertisement advertisement) { ... }
默认情况下,ApiController希望传入的任何内容都能表示URL参数,因此您需要为要在请求体中发布的任何数据提供该[FromBody]。
[System.Web.Http.HttpPost]修饰您的Post方法,这样它就不会认为它是MVC版本的[System.Web.Mvc.HttpPost]。确保放入全部内容,因为[HttpPost]也将缺省为MVC版本。将Test重命名为Post可能也不是一个坏主意,尽管您可能会将其用于单元测试方法,因此对此不太确定。
Post() JSON中发送带有advertisement的数据https://stackoverflow.com/questions/30544009
复制相似问题