Like the title says, I have an angular application that communicates with a .Net server, and I am having an issue with httpPost. Before I say further, here is the code:
component:
async addStudent() {
this.studentData = await this.studentService.addStudent(this.newStudentData).toPromise();
}
Service:
addStudent(studentNew: Student): Observable<Student[]> {
return this.http.post<Student[]>(this.baseUrl + 'api/Student/addStudents', studentNew, httpOptions)
.pipe(catchError(this.handleErrorNew.bind(this)));
httpOptions:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8'
})
};
Controller:
[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);
}
}
Model:
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; }
}
Now, whenever the API is called using the POST from angular, to add to the database, the variable addStudent is for somereason empty.
The call to the action is definitely working, because I am getting the "false" response on the clientside, from the "catch(Exception e)" part of the server.
System.ArgumentNullException: Value cannot be null.
This is what I saw on the console.
Any thoughts on why the server is unable to receive the object? Thank you!
UPDATE 1
There are a few other POST calls in my application with other models, and surprisingly, all of them are working fine, except this one.
UPDATE 2
From further digging into the backend, I have found a few interesting points. As a start, I have set a breakpoint at the start of the function in the controller, and I have noticed that the entire variable addStudent is literally set to null, not the individual class items in the variable, but the variable as a whole is set to null.
Just as a test, I have then removed the [FromBody] part like this:
public IActionResult addStudents(Student addStudent)
and now, when I run the application with the breakpoint and viewed the variable addStudent, all the class items are being displayed, but the values of all the items are null, or 0 depending on the type of the variable.
Do a debug to see which value is NULL, is it addStudent is NULL or one of property is NULL?
It feels like it's because of the framework not able to create an instance of Student object based on the post body.
Have a look at the client side to see the exactly data that post and check the server side see how is the addStudent looks like
FYI