Blazor Server 应用使用标准的 ASP.NET Core 应用程序,在服务端执行 .NET 代码 。在 Blazor Server 应用程序中,我们可以像在 ASP.NET Core Web 应用程序中那样,使用相同的方式访问任意 .NET 库或服务端功能 。这其中的一项功能是,使用 HTTP Client 实例向第三方 Web API 发送 HTTP 请求 。在本教程中,我将向您展示创建 HTTP Client 实例的不同方法 。另外,我还会向您展示如何在 Blazor Server 应用程序中使用第三方 API 来获取和显示数据 。
下载源码[2]
一、第三方 Web API 概览
我们将开发一个 Blazor Server 应用程序,该应用允许用户在 Blazor 页面组件上输入国家代码和年份,然后我们将调用第三方 API 以获取指定国家和年份的公共假期列表 。我们使用的第三方 API 是Nager.Date[3],它是一个全球公共假期 API 。
public class HolidayRequestModel
{
public string CountryCode { get; set; }
public int Year { get; set; }
}
HolidayResponseModel.cs
public class HolidayResponseModel
{
public string Name { get; set; }
public string LocalName { get; set; }
public DateTime? Date { get; set; }
public string CountryCode { get; set; }
public bool Global { get; set; }
}
public class HolidaysApiService : IHolidaysApiService
{
private readonly IHttpClientFactory _clientFactory;
public HolidaysApiService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<List<HolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new List<HolidayResponseModel>();
var url = string.Format("https://date.nager.at/api/v2/PublicHolidays/{0}/{1}",
holidaysRequest.Year, holidaysRequest.CountryCode);
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/vnd.github.v3+json");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
result = JsonSerializer.Deserialize<List<HolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.Empty<HolidayResponseModel>().ToList();
}
return result;
}
}
在上面的 GetHolidays 方法中,我们首先为第三方 API 创建了一个 URL,并将国家代码和年份参数添加到 URL 中 。
var url = string.Format("https://date.nager.at/api/v2/PublicHolidays/{0}/{1}", holidaysRequest.Year, holidaysRequest.CountryCode);
接下来,我们创建了 HttpRequestMessage 对象并配置它以向第三方 API URL 发送 HTTP GET 请求 。
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/vnd.github.v3+json");
有了 HttpClient 对象之后,我们简单地调用它的 SendAsync 方法来发送一个 HTTP GET 请求 。
var response = await client.SendAsync(request);
如果 API 调用成功,我们使用下面这行代码将其响应读取为字符串 。
var stringResponse = await response.Content.ReadAsStringAsync();
最后,我们使用 JsonSerializer 类的 Deserialize 方法反序列化该响应 。
result = JsonSerializer.Deserialize<List<HolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
public class HolidaysApiService : IHolidaysApiService
{
private readonly IHttpClientFactory _clientFactory;
public HolidaysApiService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<List<HolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new List<HolidayResponseModel>();
var url = string.Format("api/v2/PublicHolidays/{0}/{1}",
holidaysRequest.Year, holidaysRequest.CountryCode);
var request = new HttpRequestMessage(HttpMethod.Get, url);
var client = _clientFactory.CreateClient("HolidaysApi");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
result = JsonSerializer.Deserialize<List<HolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.Empty<HolidayResponseModel>().ToList();
}
return result;
}
}
public class HolidaysApiService : IHolidaysApiService
{
public HttpClient Client { get; }
public HolidaysApiService(HttpClient client)
{
client.BaseAddress = new Uri("https://date.nager.at/");
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
Client = client;
}
public async Task<List<HolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new List<HolidayResponseModel>();
var url = string.Format("api/v2/PublicHolidays/{0}/{1}",
holidaysRequest.Year, holidaysRequest.CountryCode);
var response = await Client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
result = JsonSerializer.Deserialize<List<HolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.Empty<HolidayResponseModel>().ToList();
}
return result;
}
}
可以将 HttpClient 对象密封在一个类型化客户端中,而不公开为 public 属性 。然后,我们可以在服务内部的任意方法中使用这个客户端 。
public class HolidaysApiService : IHolidaysApiService
{
private readonly HttpClient _httpClient;
public HolidaysApiService(HttpClient client)
{
_httpClient = client;
}
public async Task<List<HolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new List<HolidayResponseModel>();
var url = string.Format("api/v2/PublicHolidays/{0}/{1}",
holidaysRequest.Year, holidaysRequest.CountryCode);
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
result = JsonSerializer.Deserialize<List<HolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.Empty<HolidayResponseModel>().ToList();
}
return result;
}
}
再次运行应用程序,并提供国家代码和年份值,您应该能够看到以下公共假期列表 。
到此这篇关于Blazor Server 应用程序中进行 HTTP 请求的文章就介绍到这了,更多相关Blazor Server内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!