Vla*_*lad 4 c# asp.net-web-api2
我现在正在玩竹子.
我的[HttpGet]Web API 2控制器中有一个方法:
[HttpGet]
public LanguageResponse GetLanguages(LanguageRequest request)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我的网址看起来像这样
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)"}
Run Code Online (Sandbox Code Playgroud)
这有点奇怪,因为我正在使用GET.
如果我添加Content-Type:application/json,则不会抛出异常,但是方法的request参数设置为null.
在我的客户端代码中,情况更糟.我无法设置Content-Type标题,因为我没有Content在我HttpRequestMessage的内容中,如果我设置内容,它会抱怨我使用了错误的动词.
Cod*_*ter 10
正如在为什么我们必须在ASP.NET Web-API中指定FromBody和FromUri?,对于要从Uri解析的复杂模型,您必须使用您希望从请求Uri解析的参数的[FromUri]属性:
[HttpGet]
public LanguageResponse GetLanguages([FromUri] LanguageRequest request)
{
...
}
Run Code Online (Sandbox Code Playgroud)
否则,模型绑定器将抱怨缺少的Content-Type标头,因为它需要知道如何解析请求主体,无论如何在GET请求上丢失或为空.
要为具有正文(POST,PUT,...)的请求设置客户端的内容类型,请参阅如何为HttpClient请求设置Content-Type标头?.
| 归档时间: |
|
| 查看次数: |
5995 次 |
| 最近记录: |