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


当前回答

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

如果你有这样的json:

{
    "shoeSize": 10.5
}

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

class Shoe{
    public int shoeSize;
}

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

其他回答

添加一行

        ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

到function protected void Application_Start()在Global.asax.cs中为我修复了类似的问题。净MVC3。

我有点晚了,但是任何人在使用控制器时偶然发现一个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;
    }

希望这能有所帮助。

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

... 在控制器中

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/

我对此很晚了,但也有类似的问题,在经过一天的大量回答和背景资料后,我找到了最简单/轻量级的解决方案,将一个或多个参数传递回Web API 2 Action如下:

这里假设您知道如何使用正确的路由设置Web API控制器/动作,如果不知道,请参考:https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api。

首先是控制器动作,这个解决方案还需要Newtonsoft。Json库。

[HttpPost]
public string PostProcessData([FromBody]string parameters) {
    if (!String.IsNullOrEmpty(parameters)) {
        JObject json = JObject.Parse(parameters);

        // Code logic below
        // Can access params via json["paramName"].ToString();
    }
    return "";
}

客户端使用jQuery

var dataToSend = JSON.stringify({ param1: "value1", param2: "value2"...});
$.post('/Web_API_URI', { '': dataToSend }).done(function (data) {
     console.debug(data); // returned data from Web API
 });

我发现的关键问题是确保您只发送一个整体参数回Web API,并确保它没有名称,只有值{":dataToSend},否则您的值将在服务器端为空。

通过这种方式,您可以以JSON结构向Web API发送一个或多个参数,并且不需要在服务器端声明任何额外的对象来处理复杂的数据。JObject还允许您动态遍历传入的所有参数,以便在参数随时间变化时实现更容易的可伸缩性。希望这能帮助像我一样挣扎的人。

因为你只有一个参数,你可以尝试用[FromBody]属性来修饰它,或者改变方法来接受一个带值的DTO作为属性,就像我在这里建议的:MVC4 RC WebApi参数绑定

更新:官方ASP。NET网站今天更新了一个很好的解释:https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1

简而言之,当在body中发送单个简单类型时,只发送带有等号(=)前缀的值,例如body:

=测试