WebAPI为HttpGet抛出415错误

时间:2015-06-25 21:53:51

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

我现在正在玩竹子。

我的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标头,因为我的Content中没有HttpRequestMessage,如果我设置内容,则会抱怨我使用了错误的动词。

1 个答案:

答案 0 :(得分:8)

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?