在.net core 5应用程序中调用外部api
我为公共假期创建了一个 Web API 应用程序。
这是类 Pho
public class Pho
{
public DateTime date { get; set; }
public string localName { get; set; }
public string countryCode { get; set; }
}
这里是我尝试调用 API 的代码
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://date.nager.at/api/v3/PublicHolidays/2017/FR");
using (HttpResponseMessage response = await client.GetAsync(""))
{
var responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return Ok(responseContent);
}
}
它不起作用,我不知道如何修复它
I created a web API application for public holidays.
Here is the class Pho
public class Pho
{
public DateTime date { get; set; }
public string localName { get; set; }
public string countryCode { get; set; }
}
Here the code I tried to call the API
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://date.nager.at/api/v3/PublicHolidays/2017/FR");
using (HttpResponseMessage response = await client.GetAsync(""))
{
var responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return Ok(responseContent);
}
}
It didn't work and I didn't know how to fix it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试修复 uri
try to fix uri
您的代码无法正常工作的可能原因之一是您尝试在客户端尚未初始化时设置 BaseAddress。
要在初始化 HttpClient 时添加 BaseAddress,您应该这样做:
One of the possible reasons your code is not working is because you're trying to set BaseAddress when the client hasn't been initialized yet.
To add BaseAddress at the time of intializing HttpClient you should do it this way: