在MVC4(RC)和.NET Framework 4.5(RC)中将JSON传递给WebApi [英] Passing JSON to WebApi in MVC4(RC) and .NET Framework 4.5(RC)

查看:323
本文介绍了在MVC4(RC)和.NET Framework 4.5(RC)中将JSON传递给WebApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试将模型从类库传递到RESTful网络API.问题是,我收到异常:没有MediaTypeFormatter可用于从媒体类型为"undefined"的内容读取"EnvironmentHeartbeatModel"类型的对象.

现在使用小提琴手,如果我将标头的内容类型更改为application/json,则一切正常.但是,在我的客户代码中:

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 :

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;

    }
}


HttpClient对象不允许我添加Content-Type标头.我可以添加一个Accept标头,所以我尝试添加一个带有application/json的accept标头,但没有结果.

在我的API控制器中,我在传入的参数上添加了[FromUri]和[FromBody]属性.

有人吗?

谢谢!


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!

推荐答案

是否不应该序列化模型并从中创建一个httpconent元素?

然后在该元素上设置ContentType
Should you not be serializing the model and creating an httpconent element out of that ?

Then set the ContentType on that element
  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;
  }



我通常只使用client.PostAsync,但它应该可以工作.

可能是错误的!



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

Could be wrong though !


技巧是将BaseUrl添加到客户端,然后将路径插入PostAsJsonAsync中,而不是将整个URL传递到PostAsJsonAsync中.无论如何,谢谢您的回复!
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!


嗯,谢谢您的回答.抱歉,如果我把您引向错误的方向.
Ah thanks for the answer. Sorry if i lead you down the wrong path.


这篇关于在MVC4(RC)和.NET Framework 4.5(RC)中将JSON传递给WebApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆