Web Api方法没有获取发布的数据。缺什么?

时间:2014-05-24 00:34:13

标签: c# javascript asp.net asp.net-web-api

我尝试使用ASP.NET WebApi 2实现臭名昭着的Todo应用程序。

Todo模特:

public class Todo
{
    public int Id { get; set; }
    public string Title { get; set; }
}

WebApi Post:

public void Post([FromBody]Todo todo)
 {   
     // code to handle post.
 }

Javascript点击

$("#add").click(function(e) {               
      var todo = {
      "Id": 20000,
      "Title": "Hello world"                    
   };
   $.post( "http://localhost:51386/api/todo", JSON.stringify(todo))
      .done(function( data ) {
        alert( "Data Loaded: " + data );
   });              
});

我的HTTP请求正文如下:

{"Id":20000,"Title":"Hello world"}

使用默认路线。

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

当我调试方法Post时,它总是为空。究竟我错过了什么?

1 个答案:

答案 0 :(得分:0)

根据您的示例代码,我能想到的是您的配置中没有包含JSON Formatter。它应该是这样的:

    System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());

Content-Type=application/json仅在您设置正确的格式化程序时才有效。

相关问题