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

其他回答

添加一行

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

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

我在《小提琴手》里也遇到了同样的问题。我已经有Content-Type: application/json;请求头中的charset=utf-8或Content-Type: application/json。

我的请求体也是一个普通的字符串,在Fiddler中我写了:{'controller':'ctrl'}。这使得POST方法中的字符串参数为空。

修正:记住使用引号,从而表示字符串。也就是说,我通过编写“{'controller':'ctrl'}”来修复它。(注意:在编写JSON时,要么一定要使用撇号,要么像这样转义引号:"{\"controller\":\"ctrl\"}")。

这个链接帮助了我:http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

基本上,它说你应该为参数使用一个空名称:

public string Post([FromBody]string myParameter){ 
...
}  

$.post("/api/dosomething", { '' : "myvalue" });

经过一些尝试后,我认为默认行为是正确的,没有什么可以破解的。

唯一的技巧是:如果你的post方法参数是如下所示的字符串,你应该在正文中发送一个带有双引号的普通字符串(当使用ajax或postman时),例如:

//send "{\"a\":1}" in body to me, note the outer double quotes
[HttpPost("api1")]
public String PostMethod1([FromBody]string value)
{
    return "received " + value; //  "received {\"a\":1}"
}

否则,如果你在post正文中发送了一个没有外双引号和转义内引号的json字符串,那么它应该能够被解析为模型类(参数类型),例如,{"a":1, "b":2}

public class MyPoco{
    public int a;
    public int b;
}

//send {"a":1, "b":2} in body to me
[HttpPost("api2")]
public String PostMethod2([FromBody]MyPoco value)
{
    return "received " + value.ToString();  //"received your_namespace+MyPoco"
}

如果你确定你发送的JSON,那么你必须仔细跟踪你的API:

安装Microsoft.AspNet.WebApi.Tracing包 添加config.EnableSystemDiagnosticsTracing ();在WebApiConfig类的Register方法中。

现在查看Debug输出,您可能会发现一个无效的ModelState日志条目。

如果ModelState无效,你可以在它的Errors中找到真正的原因:

没有人能猜到这样一个例外:

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)