自从升级到RC的WebAPI,我有一些真正奇怪的问题时调用POST在我的WebAPI。 我甚至回到了在新项目上生成的基本版本。所以:

public void Post(string value)
{
}

提琴手喊道:

Header:
User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29

Body:
{
    "value": "test"
}

当我调试时,字符串“value”永远不会被赋值。它总是NULL。 有人有这个问题吗?

(我第一次看到这个问题是在一个更复杂的类型上)

这个问题不仅仅局限于ASP。在asp.net MVC 4中,同样的问题出现在一个新的ASP。NET MVC 3项目后RC安装


当前回答

我有点晚了,但是任何人在使用控制器时偶然发现一个NULL值,只要在POST请求的前面添加“=”就可以了。

当我使用application/json Content-Type时,控制器也传递了一个NULL值。注意下面的“application/x-www-form-urlencoded”内容类型。然而,API的返回类型是“application/json”。

 public static string HttpPostRequest(string url, Dictionary<string, string> postParameters)
    {
        string postData = "=";

        foreach (string key in postParameters.Keys)
        {
            postData += HttpUtility.UrlEncode(key) + "="
                  + HttpUtility.UrlEncode(postParameters[key]) + ",";
        }

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        myHttpWebRequest.Method = "POST";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

        myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
        myHttpWebRequest.ContentLength = data.Length;

        Stream requestStream = myHttpWebRequest.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

        Stream responseStream = myHttpWebResponse.GetResponseStream();

        StreamReader myStreamReader = new StreamReader(responseStream, System.Text.Encoding.Default);

        string pageContent = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        responseStream.Close();

        myHttpWebResponse.Close();

        return pageContent;
    }

其他回答

尝试创建一个类作为数据模型,然后发送一个具有与数据模型类属性匹配的属性的JSON对象。(注:我已经测试了这个,它与我今天刚刚下载的最新的MVC 4 RC 2012一起工作)。

public HttpResponseMessage Post(ValueModel model)
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, "Value Recieved: " + model.Value);
}

public class ValueModel
{
    public string Value { get; set; }
}

下面的JSON对象以HTTP-POST正文形式发送,内容类型为application/ JSON

{ "value": "In MVC4 Beta you could map to simple types like string, but testing with RC 2012 I have only been able to map to DataModels and only JSON (application/json) and url-encoded (application/x-www-form-urlencoded body formats have worked. XML is not working for some reason" }

我认为必须创建数据模型类的原因是假定简单值来自url参数,而假定单个复杂值来自主体。它们确实有[FromBody]和[FromUrl]属性,但使用[FromBody]字符串值仍然不适合我。看起来他们还在解决很多bug,所以我相信这在未来会改变。

编辑: 让XML在主体中工作。默认的XML序列化器被更改为DataContractSerializer而不是XmlSerializer。在我的全局中放入以下一行。Asax文件修复了这个问题(参考)

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

对我来说最好的解决方案是完全HTTP,如下所示:

[Route("api/open")]
[HttpPost]
public async Task<string> open(HttpRequestMessage request)
{
    var json = await request.Content.ReadAsStringAsync();
    JavaScriptSerializer jss = new JavaScriptSerializer();            
    WS_OpenSession param = jss.Deserialize<WS_OpenSession>(json);
    return param.sessionid;
}

然后将字符串反序列化为post body中期望的对象。 对我来说,WS_OpenSession是一个包含会话id、用户和密钥的类。

您可以从那里使用param对象并访问它的属性。

非常非常有效。

我说的是从这个url来源的:

http://bizcoder.com/posting-raw-json-to-web-api

问题是你的动作方法期望一个简单的类型,即字符串参数值。您所提供的是一个对象。

你的问题有两个解决方案。

创建一个具有“value”属性的简单类,然后将该类用作参数,在这种情况下,Web API模型绑定将从请求中读取JSON对象,并将其绑定到参数对象“values”属性。 只要传递字符串值“test”,它就会工作。

总有一天,我只是有同样的问题,在我的情况下,问题是,类,我是使用json容器,没有得到和设置定义,所以,API不知道如何填充json数据到实例。

我的示例json类是。

public class Usuario
{
    public int id { get; set; }
    public string nombre { get; set; }
}

如你所见,你分别有get和set,所以它会填充。

如果你删除了它们,你会得到创建类的空实例的帖子。

我知道这不是问题的答案,但我在寻找解决问题的方法时偶然发现了它。

在我的情况下,复杂类型没有被绑定,但我没有做一个POST,我正在做一个GET与查询字符串参数。解决方案是在参数中添加[FromUri]:

public class MyController : ApiController
{
    public IEnumerable<MyModel> Get([FromUri] MyComplexType input)
    {
        // input is not null as long as [FromUri] is present in the method arg
    }
}