Click here to Skip to main content
15,888,908 members
Please Sign up or sign in to vote.
4.67/5 (3 votes)
Hey guys,

I'm trying to pass a model from a class library to a RESTful web-api. Problem is, that I receive an exception : No MediaTypeFormatter is available to read an object of type 'EnvironmentHeartbeatModel' from content with media type 'undefined'.

Now using fiddler, if I change the content-type of the header to application/json, everything works fine. However, in my client code :
C#
public class RestApiInvocations<T>
{
    public HttpResponseMessage Post(string url, T model)
    {
        HttpResponseMessage result = null;
        HttpClient client = new HttpClient();
        try
        {
             result = client.PostAsJsonAsync(url, model).Result;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
        }
        return result;

    }
}

The HttpClient object doesn't allow me to add a Content-Type header. I CAN add an Accept header, so I tried to add an accept header with application/json, but without result.

In my API controller, I added the [FromUri] and [FromBody] attributes on the incomming parameters.

Anyone?

Thanks!
Posted

Should you not be serializing the model and creating an httpconent element out of that ?

Then set the ContentType on that element
C#
  JsonSerializerSettings _settings = new JsonSerializerSettings();
  JsonSerializer ser = JsonSerializer.Create(_settings);
  JObject j = JObject.FromObject(model, ser);
  HttpContent content = new StringContent(j.ToString());
  content.Headers.ContentType = new  System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
try
  {
      result = client.PostAsJsonAsync(url, model).Result;
  }


I generally just use the client.PostAsync but it should work.

Could be wrong though !
 
Share this answer
 
Comments
Eduard Keilholz 20-Jun-12 15:53pm    
The trick is to add a BaseUrl to the client, and insert the path in the PostAsJsonAsync, in stead of just passing the entire url to the PostAsJsonAsync.

Thanks for your reply anyway!
The trick is to add a BaseUrl to the client, and insert the path in the PostAsJsonAsync, in stead of just passing the entire url to the PostAsJsonAsync. Thanks for your reply anyway!
 
Share this answer
 
Ah thanks for the answer. Sorry if i lead you down the wrong path.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900