gpt4 book ai didi

c# - 使用 PostAsJsonAsync 调用 Web API

转载 作者:行者123 更新时间:2023-11-30 17:46:11 25 4
gpt4 key购买 nike

我是一个尝试调用 web api 方法的新手。

我有一个四边形对象:

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;
}

}

我的 web api post 方法做的事情非常简单。它接受一个 Quadrilateral 对象,并返回一个 Quadrilateral 的子类型,一个矩形:

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 方法如下所示:

public Quadrilateral Post(Quadrilateral q)
{
return new Rectangle(q);
}

我创建一个四边形对象,为成员分配值。然后我尝试使用以下代码调用我的 web api:

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;
}
}

调试显示 web api post 方法被命中,但 Quadrilateral 对象现在只包含 0.0 的所有 double 成员。为什么 post 方法没有得到我要发送的对象?

最佳答案

我假设您的问题现在已经解决,但这可能是因为您在 post 方法中省略了 [FromBody] 属性。你可以尝试:

public Quadrilateral Post([FromBody] Quadrilateral q)
{
return new Rectangle(q);
}

关于c# - 使用 PostAsJsonAsync 调用 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com