Calling web API using PostAsJsonAsync
I am a newbie trying to call web api method.
i has a four-sided object:
public class Quadrilateral
{
public double SideA { get; private set; }
public double SideB { get; private set; }
public double SideC { get; private set; }
public double SideD { get; private set; }
public double AngleAB { get; private set; }
public double AngleBC { get; private set; }
public double AngleCD { get; private set; }
public double AngleDA { get; private set; }
public virtual string Name { get { return "Generic Quadrilateral"; } }
public virtual string Description { get { return "A quadrilateral that has no specific name for its shape"; } }
public Quadrilateral(double sideA, double sideB, double sideC, double sideD,
double angleAB, double angleBC, double angleCD, double angleDA)
{
SideA = sideA;
SideB = sideB;
SideC = sideC;
SideD = sideD;
AngleAB = angleAB;
AngleBC = angleBC;
AngleCD = angleCD;
AngleDA = angleDA;
}
}
my web mail api method does something very simple. it takes a four-sided object and returns the subtype Quadrilateral, a rectangle:
public class Rectangle : Quadrilateral
{
public override string Name { get { return "Rectangle"; } }
public override string Description { get { return "A quadrilateral with equal opposite sides and 4 right angles"; } }
public Rectangle(Quadrilateral q) :
base(q.SideA, q.SideB, q.SideC, q.SideD,
q.AngleAB, q.AngleBC, q.AngleCD, q.AngleDA) { }
}
web api post method looks like this:
public Quadrilateral Post(Quadrilateral q)
{
return new Rectangle(q);
}
i create a four-sided object by assigning member values. then I am trying to call my web api using the following code:
readonly string baseUri = "http://localhost:43798/";
readonly string controller = "api/quadrilateral";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync(controller, quadrilateral);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<Quadrilateral>();
}
else
{
return null;
}
}
Debugging shows the web api post method has hit, but the four-way object now contains only 0.0 for all of its double members. why doesn't the post method get the object I'm trying to post?
+3
source to share
2 answers
What json value are you posting? Are you sure you are getting the correct json before posting?
Try to clear the receiving headers,
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync(controller, quadrilateral);
0
source to share