I am bamboozled right now.
I have an [HttpGet]
method in my Web API 2 controller:
[HttpGet]
public LanguageResponse GetLanguages(LanguageRequest request)
{
...
}
My url looks like this
http://localhost:1234/api/MyController/GetLanguages?Id=1
When try to call it (for example, via Postman), I recieve HTTP error 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)"}
Which is kind of weird because I am using a GET.
If I add Content-Type:application/json
, the exception will not be thrown, but then method's request
parameter is set to null
.
In my client code it's even worse. I cannot set the Content-Type
header since I don't have Content
in my HttpRequestMessage
and if I set the content, it complains I am using a wrong verb.
The As explained in Why do we have to specify FromBody and FromUri in ASP.NET Web-API?, for a complex model to be parsed from the Uri, you'll have to use the [FromUri] attribute on the parameter you wish to be parsed from the request Uri:
[HttpGet]
public LanguageResponse GetLanguages([FromUri] LanguageRequest request)
{
...
}
Otherwise the model binder will complain about the missing Content-Type header, as it needs to know how to parse the request body, which is missing or empty on a GET request anyway.
To set the content type for your client on requests that do have a body (POST, PUT, ...) see How do you set the Content-Type header for an HttpClient request?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With