Angular 和 .Net 核心应用程序 httpPost 发送 null object

Angular and .Net core application httpPost sends null object

如标题所述,我有一个与 .Net 服务器通信的 angular 应用程序,但我遇到了 httpPost 问题。在我进一步说之前,这是代码:

组件:

async addStudent() {
    this.studentData = await this.studentService.addStudent(this.newStudentData).toPromise();
}

服务:

addStudent(studentNew: Student): Observable<Student[]> {
    return this.http.post<Student[]>(this.baseUrl + 'api/Student/addStudents', studentNew, httpOptions)
    .pipe(catchError(this.handleErrorNew.bind(this)));

http选项:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json; charset=utf-8'
  })
};

控制器:

[HttpPost("[action]")]
public IActionResult addStudents([FromBody]Student addStudent)
{
    try
    {
        using (var dbObj= new dataBase())
        {
            dbObj.Add<Student>(addStudent);
            dbObj.SaveChanges();
            var students= new List<Student>();
            try{
                students= dbObj.studentsTable.ToList();
            } catch (Exception e) {
                Console.WriteLine(e);
            }
            return Json(students);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        return Json(false);
     }
}

型号:

public class Student
{
    public int studentId { get; set; }
    public int studentNum { get; set; }
    public int sectionNum { get; set; }
    public string country { get; set; }
    public string state { get; set; }
    public string city { get; set; }
    public long dateJoined { get; set; }
    public long dateGraduated { get; set; }
}

现在,每当使用 angular 中的 POST 调用 API 以添加到数据库时,变量 addStudent 出于某种原因为空。 对操作的调用肯定有效,因为我在客户端从服务器的 "catch(Exception e)" 部分收到 "false" 响应。 System.ArgumentNullException: Value cannot be null. 这是我在控制台上看到的。

关于为什么服务器无法接收 object 的任何想法?谢谢!

更新 1

在我的应用程序中还有其他一些 POST 调用与其他模型,令人惊讶的是,除了这个之外,它们都工作正常。

更新 2

通过深入挖掘后端,我发现了几个有趣的点。 首先,我在控制器中函数的开头设置了一个断点,我注意到整个变量 addStudent 字面上设置为 null,而不是变量中的单个 class 项,而是变量整体设置为null。

作为测试,我删除了 [FromBody] 部分,如下所示:

public IActionResult addStudents(Student addStudent)

现在,当我 运行 带有断点的应用程序并查看变量 addStudent 时,所有 class 项目都被显示,但所有项目的值都是空的,或 0取决于变量的类型。

调试一下,看看哪个值是 NULL,是 addStudent 是 NULL 还是 属性 之一是 NULL?

感觉是因为框架无法根据post body创建Student对象的实例。

查看客户端以查看 post 的确切数据并查看服务器端以查看 addStudent 的样子

仅供参考

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2#input-formatters

如果您使用的是 .NET Core,那么您的 API 控制器中会缺少这个小属性,如下所示。

否则我不想添加这一行请像下面这样写你的控制器

    [HttpPost]
    [Route("PostCustomer")]
    public async Task<IActionResult> PostCustomer([FromBody] Customer customer) // Add [FromBody] attribute before parameter.
    {
        // Do Some Code
        return Ok();
    }