Schming
Schming

Reputation: 51

How do I use the response from a postasync call?

I have a webApi set up that has a PostStudent method. The API call works fine and creates a new student in the DB, but I can't get it to return the value in the response body. I have tried returning Ok(newStudent) and Created("~/api/poststudent", newStudent) but neither of them have returned the newStudent value that I need.

I have gone through all of the response and can't find the actual newStudent object. Is it there and I am just missing it or do I have a problem with my code?

This is the PostStudent method from the API;

var newStudent = new Student
{
  studentId = nextStudentId,
  studentFirstName = studentEntry.StudentFirstName,
  studentLastName = studentEntry.StudentLastName,
  studentDOB = studentEntry.StudentDob,
  studentEmergencyContactName = studentEntry.StudentEmergencyContactName,
  studentEmergencyContactNum = studentEntry.StudentEmergencyContactNum,
  ticketNumber = studentEntry.TicketNumber
};

db.Student.Add(newStudent);

try
{
  db.SaveChanges();
}
catch (DbUpdateException)
{
  if (StudentExists(newStudent.studentId))
    return BadRequest("That student id already exists");
    throw;
}
return Ok(newStudent.studentId);
// return Created("~/api/poststudent", newStudent);     
}

This is where I call postasync and try to save the response body;

var response = client.PostAsync("api/poststudent", content);
return response.Result.Content.ReadAsStringAsync().ToString();

And this is where I want to use the value;

var newStudentId = controller.PostStudent(studentFirstName, studentLastName, studentDob, ticketNumber);
var url = "~/AddGuardian/AddGuardian/" + newStudentId;
Response.Redirect(url);

I hope someone can help me. I never thought redirecting to another page would be so damn hard!

Cheers.

Upvotes: 0

Views: 1785

Answers (2)

Sascha Gottfried
Sascha Gottfried

Reputation: 3329

There are 2 official tutorials for quickstarting a ASP.NET WebApi project.

I want to recommend to work through these. If you find your application is doing things wrong, fix your application towards these samples. If your requirements differ from what is given in the samples, you can emphasize on this in your question.

Upvotes: 0

David
David

Reputation: 219037

You're not awaiting the async calls:

var response = await client.PostAsync("api/poststudent", content);
return (await response.Result.Content.ReadAsStringAsync()).ToString();

Upvotes: 1

Related Questions