WebAPI 为 HttpGet 抛出 415 错误

WebAPI throws 415 error for HttpGet

我现在被蒙蔽了。

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

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

我的 url 看起来像这样 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 header,因为我的 HttpRequestMessage 中没有 Content,如果我设置内容,它会抱怨我使用了错误的动词。

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 header,因为它需要知道如何解析请求 body,它在 GET 请求中丢失或为空反正。

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