I have written a ServiceHelper class that will assist with POST's to a C# Web API controller
public class ServiceHelper<TResponse, TRequest> : IServiceHelper<TResponse, TRequest>
{
public TResponse Execute
(
string endpoint,
string controller,
string action,
TRequest request,
string format = "application/json"
)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(endpoint);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(format));
var response = httpClient.PostAsJsonAsync(String.Format("{0}/{1}", controller, action),
request).Result;
return response.Content.ReadAsAsync<TResponse>().Result;
}
}
}
I keep on getting
Additional information: No MediaTypeFormatter is available to read an object of type 'ReadMotorVehiclesWorkflowResponse' from content with media type 'text/html'.
Any ideas on how to fix this?
Apparently the server returns HTML where you expect JSON, and obviously there is no way to deserialize a TResponse
from HTML...
I suspect the server is actually returning an error code, and the HTML is just a visual representation of the error.
You should call response.EnsureSuccessStatusCode()
to make sure the response indicates success (typically 200 OK). If it's not the case, it will raise an exception.
Ok, the problem was that the application pool's .NET version was set to version 2.0 while the web API was written for .NET version 4.0, I changed the version and it is now working as expected.
It is worth while to note that it is a good idea to call response.EnsureSuccessStatusCode()
as mentioned in the answer below.
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