无法在asp.net web api中将json对象传递给控制器

时间:2016-09-28 06:28:31

标签: json asp.net-web-api

我是web api的新手,在将json消息传递给web api控制器时无法找到错误。我正在使用fiddler客户端发布复杂类型(模型对象)。我的模型总是为空。它不是从json post对象读取的。我究竟做错了什么?

我的模特:

  public class LocationModel
           {


 public int Customer {get; set;}
    public string Name { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string Area { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }


}

我的控制器:

public class LocationController : ApiController
    {
[HttpPost]
        public bool AddLocation([FromBody] LocationModel model)
        {
            MysqlRepository reps = new MysqlRepository();
            if (reps.LocationInsert(model))
                {
                    return true;

                }
                else
                {
                    return false;

                }
            }


    }

Json消息(使用fiddler客户端发布):

var LocationModel = {
Customer:9,
            Name: "test",
AddressLine1:"rrr",
AddressLine2:"rrr",
Area:"ddd",
City:"ddd",
State:"cooo",
Country:"kkk"
}

$.ajax({
 url: 'api/Location',
 type: 'POST',
 data: JSON.stringify(LocationModel),
 dataType: 'json',
 contentType: "application/json",
 success: function (data) {

 }
});

1 个答案:

答案 0 :(得分:0)

作为fiddler工具的新手我在身体传递了标题信息...这就是为什么输入没有从工具传递.... 正确的方法是传递提琴手身体:

{
"Customer":9,
"Name": "test",
"AddressLine1":"rrr",
"AddressLine2":"rrr",
"Area":"ddd",
"City":"ddd",
"State":"cooo",
"Country":"kkk"
}