WebApi请求参数为null

时间:2016-05-11 11:12:51

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

以下是我的模特

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Course> Courses { get; set; }
}

public class Course
{
    public string Name { get; set; }
    public string Details { get; set; }
}

这是我的WebApi方法

[HttpPost]
public void SetStudentInfo(Student student)
{
    ...
}

这是我来自JS的电话(这个有效)

$.ajax({
  async: false,
  type: "POST",
  url: "http://localhost:50067/api/Students/SetStudentInfo",
  data: {
    FirstName: "John",
    LastName: "Smith"
  },
  success: function (xhr) {
    console.log(xhr);
  },
  error: function (e) {
    console.log(e);
  }
});

这是我来自JS的电话(这个没有用)

$.ajax({
  async: false,
  type: "POST",
  url: "http://localhost:50067/api/Students/SetStudentInfo",
  data: {
    FirstName: "John",
    LastName: "Smith",
    Courses: null
  },
  success: function (xhr) {
    console.log(xhr);
  },
  error: function (e) {
    console.log(e);
  }
});

当我发送第二个请求时,WebApi方法上的整个学生都为空;它与添加嵌套对象有关,但我不确定原因,或者如何解决这个问题。

我已尝试对数据进行字符串化,但这也不起作用。

2 个答案:

答案 0 :(得分:3)

尝试将请求数据的内容类型指定为application/json,并且还需要使用JSON.stringify()函数序列化数据。

您可以复制以下代码:

var requestData = {
        FirstName: "John",
        LastName: "Smith",
        Courses: null
    };

$.ajax({
    type: "POST",
    url: "http://localhost:50067/api/Students/SetStudentInfo",
    data: JSON.stringify(requestData),
    contentType: "application/json",
    success: function (xhr) {
        console.log(xhr);
    },
    error: function (e) {
        console.log(e);
    }
});

还有一个提示。您的网络API控制器不应该是void。 Api控制器应该总是返回一些内容,例如IHttpActionResult

[HttpPost]
public IHttpActionResult SetStudentInfo(Student student)
{
    //process your data
    return Ok();// or BadRequest()
}

答案 1 :(得分:0)

您需要指定content-type之类的

contentType:"application/json"

您还需要使用JSON.stringify()方法将数据转换为JSON格式,您可以在https://stackoverflow.com/a/20226220/2931427

阅读更多详细信息

旧答案

在你的行动中试试这个:

[HttpPost]
public void SetStudentInfo([FromBody] Student student)
{
    ...
}
相关问题