【发布时间】:2019-11-10 00:00:25
【问题描述】:
正如标题所说,我有一个与 .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)”部分得到了客户端的“错误”响应。
System.ArgumentNullException: Value cannot be null.
这是我在控制台上看到的。
关于为什么服务器无法接收对象的任何想法?谢谢!
更新 1
我的应用程序中还有一些其他模型的 POST 调用,令人惊讶的是,除了这个之外,它们都运行良好。
更新 2
从进一步挖掘后端,我发现了一些有趣的点。 作为开始,我在控制器中的函数开头设置了一个断点,我注意到整个变量 addStudent 字面上设置为 null,而不是变量中的各个类项,而是变量作为一个整体是设置为空。
作为测试,我随后删除了 [FromBody] 部分,如下所示:
public IActionResult addStudents(Student addStudent)
现在,当我使用断点运行应用程序并查看变量 addStudent 时,所有类项都被显示,但所有项的值为 null,或 0,具体取决于变量的类型。
【问题讨论】:
-
如果您可以编辑您的问题并向我们展示数据是什么会有所帮助,否则您是否 100% 确定它是正确的?还要提供您的 Student 对象模型。
-
@penleychan 我 100% 确定它是正确的,因为我逐个字母地检查了它。我已经用模型编辑了这个问题。
-
困惑,
[FromBody]Student与Tracking不同的对象? -
你的后端 api 在邮递员中工作吗
-
@penleychan 对不起,错字,我已经更正了。
标签: angular typescript .net-core http-post