gpt4 book ai didi

c# - 在 C# 中从 WebApi 获取数据

转载 作者:行者123 更新时间:2023-11-30 12:48:02 27 4
gpt4 key购买 nike

我有 webapi 和她的方法:

[HttpPost, HttpGet]
[ActionName("GetData")]
public MyData GetData([FromUri] MyData data)
{
return datamanager.get(data);
}

如何调用此方法? IE。如何通过 URL 的查询部分发送 data 参数?

要调用不带参数的 get 方法,我使用以下代码:

public static async Task<myClassl> GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://sasa.com");
HttpResponseMessage response = await client.GetAsync("api/GetData");
myClassl data = await response.Content.ReadAsAsync<myClassl>();

return data ;
}

谢谢。

最佳答案

尝试以下解决方案:

HttpClient client = new HttpClient();
string baseApiAddress = ConfigurationManager.AppSettings["baseApiAddress"];
client.BaseAddress = new Uri(baseApiAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response=client.GetAsync("/api/GetData",data, new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{
var mydata = response.Content.ReadAsAsync<MyData>().Result;
}
else
{
Debug.WriteLine(response.ReasonPhrase);
}

关于c# - 在 C# 中从 WebApi 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15210876/

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