【问题标题】:WebApi request parameters are nullWebApi 请求参数为空
【发布时间】:2016-09-06 18:03:38
【问题描述】:

这是我的模型

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

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

【问题讨论】:

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


【解决方案1】:

你需要指定content-typelike

contentType:"application/json"

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

旧答案

在你的行动中试试这个:

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

【讨论】:

  • 默认从请求正文中读取复杂类型。这不会导致任何错误,但不会执行任何操作。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多