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


当前回答

添加一行

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

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

其他回答

这招对我很管用:

Create a C# DTO class, with a property for every attribute you want to pass from jQuery/Ajax public class EntityData { public string Attr1 { get; set; } public string Attr2 { get; set; } } Define the web api method: [HttpPost()] public JObject AddNewEntity([FromBody] EntityData entityData) { Call the web api as such: var entityData = { "attr1": "value1", "attr2": "value2" }; $.ajax({ type: "POST", url: "/api/YOURCONTROLLER/addnewentity", async: true, cache: false, data: JSON.stringify(entityData), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { ... } });

我发现最简单的方法来处理简单的JSON对象,我传递到MVC 6是获得类型的post参数像NewtonSoft jObject:

public ActionResult Test2([FromBody] jObject str)
{
        return Json(new { message = "Test1 Returned: "+ str }); ;
}

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

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

如果你有这样的json:

{
    "shoeSize": 10.5
}

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

class Shoe{
    public int shoeSize;
}

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

如果您正在为Xml Formatter或JSON Formatter使用DataContractSerializer,则需要摆脱它。 我在我的WebApiConfig文件中有这个:

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();
     jsonFormatter.UseDataContractJsonSerializer = true;
}

我简单地注释掉了jsonFormatter。UseDataContractJsonSerializer = true;并且我的输入参数不再为空。感谢《亡命之徒》给了我一个提示。