自从升级到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安装


当前回答

希望这能有所帮助。

在不同的评论和其他论坛中,我混合了一些片段,对我来说,这段代码是有效的…

... 在控制器中

public HttpResponseMessage Post([FromBody] string jsonData)
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, jsonData);            

        try 
        {
            string jsonString = jsonData.ToString();
            JArray jsonVal = JArray.Parse(jsonString) as JArray;
            dynamic mylist= jsonVal;
            foreach (dynamic myitem in mylist)
            {
                string strClave=string.Empty;
                string strNum=string.Empty;
                string strStatus=string.Empty;

                strClave = myitem.clave;
                strNum=myitem.num;
                strStatus = myitem.status; 
            }

... 在WebApiConfig.cs中包含这一行,以避免[FromBody]变量var jsonFormatter = config.Formatters.OfType().First()中的空值;

public static void Register(HttpConfiguration config)
    { 
            config.Routes.MapHttpRoute(
                            name: "DefaultApi",
                            routeTemplate: "api/{controller}/{id}",
                            defaults: new { id = RouteParameter.Optional }
                        );
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();  /*this line makes no more null when use [FromBody]*/
}

.... 在客户端,最重要的是在序列化数据之前连接等号(string json =" =" + SerialData;)

我正在使用的seralize

System.Web.Script.Serialization.JavaScriptSerializer serializer = new 
System.Web.Script.Serialization.JavaScriptSerializer();

        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow dr in DsCnx.Tables[0].Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in DsCnx.Tables[0].Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        SerialData= serializer.Serialize(rows);
       PostRequest("http://localhost:53922/api/Demo", SerialData);

这是我的PostRequest函数,这里的内容类型我使用的是httpWebRequest。ContentType = "application/x-www-form-urlencoded; "charset = utf - 8”;:

private static string PostRequest(string url, string SerialData)
    {         
        string result = String.Empty;
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "=" + SerialData;  
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        try
        {
            using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
            {
                if (httpWebRequest.HaveResponse && response != null)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException e)
        {
            if (e.Response != null)
            {
                using (var errorResponse = (HttpWebResponse)e.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string error = reader.ReadToEnd();
                        result = error;
                    }
                }

            }
        }

        return result.ToString();

    }

以下是我找到的一个代码示例的链接:

https://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing#jobject-and-jarray-in-aspnet-web-api

https://blog.codenamed.nl/2015/05/12/why-your-frombody-parameter-is-always-null/

其他回答

我知道OP最初是发送一个字符串,但是为了将来的参考,同样值得注意的是,畸形的JSON也将作为null到达post方法。在我的例子中,两个属性之间缺少了逗号,导致了原本正常的破坏。

仔细检查您的数据类型。dotnet模型绑定器不会将浮点数转换为整数(我假设有其他相关概念)。这将导致整个模型被拒绝。

如果你有这样的json:

{
    "shoeSize": 10.5
}

但是你的c#模型是这样的:

class Shoe{
    public int shoeSize;
}

模型绑定器将拒绝该模型,您将得到null。

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

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

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

在ASP中也遇到过类似的问题。NET Core和另一个可能的原因是ASP。NET绑定(沉默)失败,由于各种原因,如发送null被绑定到一个非null属性:

{
    "prop1":1139357,
    "prop2":1139356,

    "items":[
        {"key":"15","someprop":34,"notnullprop":null},
        {"key":"16","someprop":34,"notnullprop":null},
        {"key":"22","someprop":34,"notnullprop":null}]
}

在这种情况下,不会抛出异常,整个模型将为null,即使这种情况发生在对象层次结构的深处。

我一直在寻找这个问题的解决方案,所以我将分享我的解决方案。

如果你发布一个模型,你的模型需要有一个空的/默认的构造函数,否则模型显然不能被创建。 重构时要小心。;)