gpt4 book ai didi

c# - 将 Json 与 Web API 和 GET 请求一起使用

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

我有一个返回 json 对象的 Web API 项目。对象已正确填充,但当它们被调用应用程序接收时,它们是空的。我怀疑这与 Json 的 GET 请求被拒绝有关。

我的 API Controller 代码如下所示:

public IHttpActionResult GetThing(string id)
{
try
{
var model = new Thing(id);
var res = Json<Thing>(model);
return res;
}
catch
{
return NotFound();
}
}

此时“res”已正确填充。现在在另一(客户端)方面我有:

internal static JsonResult GetThing(string thingId)
{
return GetTask<JsonResult>(string.Format(ThingUrl, thingId));
}

当我在这里检查 JsonObject 的值时,它是空的(数据为空),但我也注意到字段“JsonRequestBehavior”的值是“DenyGet”,我怀疑这是问题所在。

我的问题是,如何将 this 的值设置为“AllowGet”,以便我可以使用填充的对象?我正在失去我剩下的一点点头发!

最佳答案

您不需要在 Controller 中将对象转换为 JSON。你应该能够让你的 Controller 代码看起来像这样:

public Thing Get(string id)
{
try
{
var model = new Thing(id);
return model;
}
catch
{
//throw not found exception
}
}

然后,当您发出请求时,请确保设置了 Accept: application/json header ,您应该是金色的。

编辑:根据您的评论,以及实际使请求不可见的代码,我只能假设您为调用 API 端点而编写的代码一定是不正确的。

它应该看起来像这样:

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("BaseUrlOfAPI");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.GetAsync("realtiveurltocontroller/thingid");
if (response.IsSuccessStatusCode)
{
Thing thing = await response.Content.ReadAsAsync<Thing>();
// Do whatever you want with thing.
}
}

有关这方面的更多信息,请参见 here

关于c# - 将 Json 与 Web API 和 GET 请求一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452151/

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