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


当前回答

我也遇到过这个问题,这就是我解决问题的方法

webapi守则:

public void Post([FromBody] dynamic data)
{
    string value = data.value;
    /* do stuff */
}

客户机代码:

$.post( "webapi/address", { value: "some value" } );

其他回答

如果您正在为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;并且我的输入参数不再为空。感谢《亡命之徒》给了我一个提示。

添加一行

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

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

在Angular中,我可以这样传递数据:

 data: '=' + JSON.stringify({ u: $scope.usrname1, p: $scope.pwd1 }),
 headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }

在Web API控制器中:

    [HttpPost]
    public Hashtable Post([FromBody]string jsonString)
    {
        IDictionary<string, string> data = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonString);
        string username = data["u"];
        string pwd = data["p"];
   ......

或者,我也可以像这样发布JSON数据:

    data: { PaintingId: 1, Title: "Animal show", Price: 10.50 } 

并且,在控制器中,接受这样的类类型:

    [HttpPost]
    public string POST(Models.PostModel pm)
    {

     ....
    }

两种方式都可以,如果你在API中有一个已经建立的公共类,那么就发布JSON,否则就发布'=' + JSON.stringify({..:…, . .:…})

如果你确定你发送的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)

在我的例子中,用Newtonsoft的[JsonObject(memberseriizable . optout)]属性装饰参数类就很管用。

例如:

[HttpPost]
[Route("MyRoute")]
public IHttpActionResult DoWork(MyClass args)
{
   ...
}

[JsonObject(MemberSerialization.OptOut)]
public Class MyClass
{
    ...
}