繁体   English   中英

WebApi请求参数为空

[英]WebApi request parameters are null

这是我的模特

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方法的整个学生为空; 这与添加嵌套对象有关,但我不确定为什么,或如何解决此问题。

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

尝试将请求数据的内容类型指定为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);
    }
});

还有一个提示。 您的Web API控制器不应为void api控制器应始终返回某些内容,例如IHttpActionResult

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

您需要指定content-type例如

contentType:"application/json"

另外,您还需要在发送数据时使用JSON.stringify()方法将数据转换为JSON格式。您可以在https://stackoverflow.com/a/20226220/2931427阅读更多详细信息

老答案

在您的操作中尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM