【问题标题】:WebAPI throws 415 error for HttpGetWebAPI 为 HttpGet 引发 415 错误
【发布时间】:2015-09-12 17:09:27
【问题描述】:

我现在被迷惑了。

我的 Web API 2 控制器中有一个 [HttpGet] 方法:

[HttpGet]
public LanguageResponse GetLanguages(LanguageRequest request) 
{
...
}

我的网址看起来像这样 http://localhost:1234/api/MyController/GetLanguages?Id=1

当尝试调用它时(例如,通过 Postman),我收到 HTTP 错误 415:

{"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 'LanguagesRequest' 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.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

这有点奇怪,因为我使用的是 GET

如果我添加Content-Type:application/json,则不会抛出异常,但是方法的request参数设置为null

在我的客户端代码中,情况更糟。我无法设置Content-Type 标头,因为我的HttpRequestMessage 中没有Content,如果我设置内容,它会抱怨我使用了错误的动词。

【问题讨论】:

    标签: c# asp.net-web-api2


    【解决方案1】:

    正如Why do we have to specify FromBody and FromUri in ASP.NET Web-API? 中所述,对于要从 Uri 解析的复杂模型,您必须在希望从请求 Uri 中解析的参数上使用 [FromUri] 属性:

    [HttpGet]
    public LanguageResponse GetLanguages([FromUri] LanguageRequest request) 
    {
        ...
    }
    

    否则模型绑定器将抱怨缺少 Content-Type 标头,因为它需要知道如何解析请求正文,无论如何,在 GET 请求上该正文丢失或为空。

    要为您的客户端设置具有正文(POST、PUT、...)的请求的内容类型,请参阅How do you set the Content-Type header for an HttpClient request?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-29
      • 2017-05-03
      • 2013-05-03
      • 2017-01-07
      • 2013-02-25
      • 2017-05-26
      • 2013-07-14
      • 2017-04-04
      相关资源
      最近更新 更多