目錄
- Blazor Server 應(yīng)用程序中進(jìn)行 HTTP 請(qǐng)求
- 一、第三方 Web API 概覽
- 二、從 Blazor Sever 應(yīng)用程序開始
- 三、在 Blazor Server 應(yīng)用程序中使用 IHttpClientFactory 創(chuàng)建 HttpClient
- 四、在 Blazor Server 應(yīng)用程序中創(chuàng)建命名 HttpClient 對(duì)象
- 五、在 Blazor Server 應(yīng)用程序中創(chuàng)建類型化 HttpClient 對(duì)象
Blazor Server 應(yīng)用程序中進(jìn)行 HTTP 請(qǐng)求
翻譯自 Waqas Anwar 2021年5月4日的文章 《Making HTTP Requests in Blazor Server Apps》 [1]

Blazor Server 應(yīng)用使用標(biāo)準(zhǔn)的 ASP.NET Core 應(yīng)用程序,在服務(wù)端執(zhí)行 .NET 代碼。在 Blazor Server 應(yīng)用程序中,我們可以像在 ASP.NET Core Web 應(yīng)用程序中那樣,使用相同的方式訪問任意 .NET 庫或服務(wù)端功能。這其中的一項(xiàng)功能是,使用 HTTP Client 實(shí)例向第三方 Web API 發(fā)送 HTTP 請(qǐng)求。在本教程中,我將向您展示創(chuàng)建 HTTP Client 實(shí)例的不同方法。另外,我還會(huì)向您展示如何在 Blazor Server 應(yīng)用程序中使用第三方 API 來獲取和顯示數(shù)據(jù)。
下載源碼[2]
一、第三方 Web API 概覽
我們將開發(fā)一個(gè) Blazor Server 應(yīng)用程序,該應(yīng)用允許用戶在 Blazor 頁面組件上輸入國(guó)家代碼和年份,然后我們將調(diào)用第三方 API 以獲取指定國(guó)家和年份的公共假期列表。我們使用的第三方 API 是Nager.Date[3],它是一個(gè)全球公共假期 API。
這是一個(gè)非常簡(jiǎn)單的 API,您可以輕松地在 Postman 中輸入以下 URL 測(cè)試此 API。
https://date.nager.at/api/v2/PublicHolidays/2021/CN
該 API 的響應(yīng)是 JSON 格式的公共假期列表,如下所示:

二、從 Blazor Sever 應(yīng)用程序開始
在 Visual Studio 2019 中創(chuàng)建一個(gè) Blazor Server 應(yīng)用程序,并新建一個(gè)名為 Models 的文件夾。在 Models 文件夾中添加以下兩個(gè)模型類,以映射上述 Holidays API 的請(qǐng)求和響應(yīng)。
HolidayRequestModel.cs
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; }
}
接下來,在 Pages 文件夾中創(chuàng)建一個(gè)新的 Razor 組件 HolidaysExplorer.razor 和代碼隱藏文件 HolidaysExplorer.razor.cs。如果您想了解有關(guān) Razor 組件和代碼隱藏文件的更多知識(shí),可以閱讀文章《Blazor 組件入門指南》。
HolidaysExplorer.razor.cs
public partial class HolidaysExplorer
{
private HolidayRequestModel HolidaysModel = new HolidayRequestModel();
private ListHolidayResponseModel> Holidays = new ListHolidayResponseModel>();
[Inject]
protected IHolidaysApiService HolidaysApiService { get; set; }
private async Task HandleValidSubmit()
{
Holidays = await HolidaysApiService.GetHolidays(HolidaysModel);
}
}
HolidaysModel 字段是 HolidayRequestModel 類的一個(gè)實(shí)例,它將幫助我們創(chuàng)建一個(gè)簡(jiǎn)單的表單來向用戶詢問國(guó)家代碼和年份。下面的代碼片段顯示了使用 HolidaysModel 對(duì)象創(chuàng)建的 Blazor 表單,其中 HandleValidSubmit 方法是使用 Blazor Form 的 OnValidSubmit 事件配置的,用戶提交表單時(shí)該方法將被調(diào)用。
EditForm Model="@HolidaysModel" OnValidSubmit="@HandleValidSubmit" class="form-inline">
label class="ml-2">Country Code:/label>
InputText id="CountryCode" @bind-Value="HolidaysModel.CountryCode" class="form-control" />
label class="ml-2">Year:/label>
InputNumber id="Year" @bind-Value="HolidaysModel.Year" class="form-control" />
button class="btn btn-primary ml-2" type="submit">Submit/button>
/EditForm>
Holidays 列表用來顯示從第三方 API 返回的假期。我們需要使用一個(gè) @foreach 循環(huán)迭代返回的假期來生成一個(gè)簡(jiǎn)單的 bootstrap 表格。
@if (Holidays.Count > 0)
{
table class="table table-bordered table-striped table-sm">
thead>
tr>
th>Date/th>
th>Name/th>
th>Local Name/th>
th>Country Code/th>
th>Global/th>
/tr>
/thead>
tbody>
@foreach (var item in Holidays)
{
tr>
td>@item.Date.Value.ToShortDateString()/td>
td>@item.Name/td>
td>@item.LocalName/td>
td>@item.CountryCode/td>
td>@item.Global/td>
/tr>
}
/tbody>
/table>
}
HolidaysExplorer.razor 視圖的完整代碼如下:
@page "/"
h3>Holidays Explorer/h3>
br />
EditForm Model="@HolidaysModel" OnValidSubmit="@HandleValidSubmit" class="form-inline">
label class="ml-2">Country Code:/label>
InputText id="CountryCode" @bind-Value="HolidaysModel.CountryCode" class="form-control" />
label class="ml-2">Year:/label>
InputNumber id="Year" @bind-Value="HolidaysModel.Year" class="form-control" />
button class="btn btn-primary ml-2" type="submit">Submit/button>
/EditForm>
br />
@if (Holidays.Count > 0)
{
table class="table table-bordered table-striped table-sm">
thead>
tr>
th>Date/th>
th>Name/th>
th>Local Name/th>
th>Country Code/th>
th>Global/th>
/tr>
/thead>
tbody>
@foreach (var item in Holidays)
{
tr>
td>@item.Date.Value.ToShortDateString()/td>
td>@item.Name/td>
td>@item.LocalName/td>
td>@item.CountryCode/td>
td>@item.Global/td>
/tr>
}
/tbody>
/table>
}
此時(shí)如果您運(yùn)行該應(yīng)用程序,您將看到一個(gè)不顯示任何假期的簡(jiǎn)單 HTML 表單。這是因?yàn)榉椒?HandleValidSubmit 是空的,我們還未調(diào)用任何 API 來獲取假期數(shù)據(jù)。

三、在 Blazor Server 應(yīng)用程序中使用 IHttpClientFactory 創(chuàng)建 HttpClient
在 Blazor Server 應(yīng)用程序中使用 HttpClient 請(qǐng)求第三方 API 有多種不同的方式,讓我們從一個(gè)基礎(chǔ)的示例開始,在該示例中我們使用 IHttpClientFactory
創(chuàng)建 HttpClient
對(duì)象。
在項(xiàng)目中創(chuàng)建一個(gè) Services 文件夾,并創(chuàng)建如下的 IHolidaysApiService 接口。該接口只有一個(gè)方法 GetHolidays,它以 HolidayRequestModel 作為參數(shù)并返回 HolidayResponseModel 對(duì)象的列表。
IHolidaysApiService.cs
public interface IHolidaysApiService
{
TaskListHolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest);
}
接下來,在 Services 文件夾中創(chuàng)建一個(gè) HolidaysApiService 類,實(shí)現(xiàn)上面的接口。
public class HolidaysApiService : IHolidaysApiService
{
private readonly IHttpClientFactory _clientFactory;
public HolidaysApiService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async TaskListHolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new ListHolidayResponseModel>();
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.DeserializeListHolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.EmptyHolidayResponseModel>().ToList();
}
return result;
}
}
在上面的 GetHolidays 方法中,我們首先為第三方 API 創(chuàng)建了一個(gè) URL,并將國(guó)家代碼和年份參數(shù)添加到 URL 中。
var url = string.Format("https://date.nager.at/api/v2/PublicHolidays/{0}/{1}", holidaysRequest.Year, holidaysRequest.CountryCode);
接下來,我們創(chuàng)建了 HttpRequestMessage 對(duì)象并配置它以向第三方 API URL 發(fā)送 HTTP GET 請(qǐng)求。
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/vnd.github.v3+json");
可以使用依賴注入 (DI) 請(qǐng)求一個(gè) IHttpClientFactory,這正是我們將其注入到前面類的構(gòu)造函數(shù)的原因。下面這行代碼使用 IHttpClientFactory 創(chuàng)建了一個(gè) HttpClient 實(shí)例。
var client = _clientFactory.CreateClient();
有了 HttpClient 對(duì)象之后,我們簡(jiǎn)單地調(diào)用它的 SendAsync 方法來發(fā)送一個(gè) HTTP GET 請(qǐng)求。
var response = await client.SendAsync(request);
如果 API 調(diào)用成功,我們使用下面這行代碼將其響應(yīng)讀取為字符串。
var stringResponse = await response.Content.ReadAsStringAsync();
最后,我們使用 JsonSerializer 類的 Deserialize 方法反序列化該響應(yīng)。
result = JsonSerializer.DeserializeListHolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
在測(cè)試該應(yīng)用程序之前,我們需要在 Startup.cs 文件中注冊(cè) HolidaysApiService 服務(wù)。我們還需要調(diào)用 AddHttpClient 方法注冊(cè) IHttpClientFactory。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingletonIHolidaysApiService, HolidaysApiService>();
services.AddHttpClient();
}
運(yùn)行應(yīng)用程序并在文本框中提供任意國(guó)家代碼和年份。點(diǎn)擊 Submit 按鈕就會(huì)在后臺(tái)調(diào)用我們的 GetHolidays 方法,然后您應(yīng)該能看到如下所示的公共假期列表。

四、在 Blazor Server 應(yīng)用程序中創(chuàng)建命名 HttpClient 對(duì)象
上面的示例適用于您正在重構(gòu)現(xiàn)有的應(yīng)用程序,希望在不影響整個(gè)應(yīng)用程序的情況下,在某些方法中使用 IHttpClientFactory 創(chuàng)建 HttpClient 對(duì)象的場(chǎng)景。如果您要?jiǎng)?chuàng)建一個(gè)全新的應(yīng)用程序,或者您想要將創(chuàng)建 HttpClient 對(duì)象的方式集中化,那么您必須使用命名 HttpClient。
下面是創(chuàng)建命名 HTTP 客戶端的好處:
- 我們可以為每個(gè) HttpClient 命名,并在應(yīng)用程序啟動(dòng)時(shí)指定與 HttpClient 相關(guān)的所有配置,而不是將配置分散在整個(gè)應(yīng)用程序當(dāng)中。
- 我們可以只配置一次命名的 HttpClient,并多次重用它調(diào)用一個(gè)特定 API 提供者的所有 API。
- 我們可以根據(jù)這些客戶端在應(yīng)用程序不同區(qū)域的使用情況,配置多個(gè)不同配置的命名 HttpClient 對(duì)象。
我們可以在 Startup.cs 文件的 ConfigureServices 方法中,使用前面用過的名為 AddHttpClient 方法指定一個(gè)命名的 HttpClient。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingletonIHolidaysApiService, HolidaysApiService>();
services.AddHttpClient("HolidaysApi", c =>
{
c.BaseAddress = new Uri("https://date.nager.at/");
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
});
}
我們需要指定客戶端的名稱(例如 HolidaysApi),我們還可以配置如上所示的 BaseAddress、DefaultRequestHeaders 和其他屬性。
配置了命名 HttpClient 之后,我們可以使用相同的 CreateClient 方法在整個(gè)應(yīng)用程序中創(chuàng)建 HttpClient 對(duì)象,不過這次我們需要指定想要?jiǎng)?chuàng)建哪個(gè)已命名的客戶端(例如 HolidaysApi)。
HolidaysApiService.cs
public class HolidaysApiService : IHolidaysApiService
{
private readonly IHttpClientFactory _clientFactory;
public HolidaysApiService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async TaskListHolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new ListHolidayResponseModel>();
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.DeserializeListHolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.EmptyHolidayResponseModel>().ToList();
}
return result;
}
}
我們?cè)?strong> CreateClient 方法中傳遞的名稱(比如 HolidaysApi)必須與我們?cè)?Startup.cs 文件中配置的名稱一致。每次調(diào)用 CreateClient 方法時(shí),都會(huì)為我們創(chuàng)建一個(gè)新的 HttpClient 實(shí)例。
另外,我們不需要在請(qǐng)求的 URL 中指定 API 主機(jī)名稱,因?yàn)槲覀冊(cè)?Startup.cs 文件中已經(jīng)指定過基地址了。
再次運(yùn)行應(yīng)用程序并提供國(guó)家代碼和年份值,您應(yīng)該能看到以下公共假期列表。

五、在 Blazor Server 應(yīng)用程序中創(chuàng)建類型化 HttpClient 對(duì)象
創(chuàng)建和使用 HttpClient 對(duì)象的第三種選擇是使用類型化客戶端。這種客戶端具有以下好處:
- 它們提供與命名客戶端同樣的功能,但無需使用字符串作為鍵。
- 它們?cè)谑褂每蛻舳藭r(shí)提供智能感知和編譯器幫助。
- 它們提供了一個(gè)單一的存儲(chǔ)單元來配置特定的 HttpClient 并與之交互。例如,我們可以配置針對(duì) Facebook API 的一個(gè)特定終端的一個(gè)類型化 HttpClient,而且該 HttpClient 可以封裝使用該特定終端所需的所有邏輯。
- 它們與依賴注入 (DI) 一起使用,可以在需要的地方注入。
要配置類型化的 HTTPClient,我們需要在 Startup.cs 文件中使用相同的 AddHttpClient 方法注冊(cè)它,但這一次,我們需要傳遞我們的服務(wù)名稱 HolidaysApiService 作為它的類型。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingletonIHolidaysApiService, HolidaysApiService>();
services.AddHttpClientHolidaysApiService>();
}
在上面的代碼片段中,HTTP 客戶端和我們的服務(wù) HolidaysApiService 都將注冊(cè)為瞬時(shí)客戶端和服務(wù)。這將允許我們?cè)诜?wù)的構(gòu)造函數(shù)中傳遞 HttpClient,如以下代碼片段所示。請(qǐng)注意,HttpClient 是如何公開為服務(wù)的 public 屬性的。
HolidaysApiService.cs
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 TaskListHolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new ListHolidayResponseModel>();
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.DeserializeListHolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.EmptyHolidayResponseModel>().ToList();
}
return result;
}
}
類型化客戶端的配置也可以不在類型化客戶端的構(gòu)造函數(shù)中指定,而在注冊(cè)期間在 Startup.cs 文件的 ConfigureServices 方法中指定。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpClientIHolidaysApiService, HolidaysApiService>(c =>
{
c.BaseAddress = new Uri("https://date.nager.at/");
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
});
}
如果您使用的是這種方式,則無需單獨(dú)注冊(cè)您的服務(wù)。您可以從 ConfigureServices 方法中刪除下面這行代碼。
services.AddSingletonIHolidaysApiService, HolidaysApiService>();
可以將 HttpClient 對(duì)象密封在一個(gè)類型化客戶端中,而不公開為 public 屬性。然后,我們可以在服務(wù)內(nèi)部的任意方法中使用這個(gè)客戶端。
public class HolidaysApiService : IHolidaysApiService
{
private readonly HttpClient _httpClient;
public HolidaysApiService(HttpClient client)
{
_httpClient = client;
}
public async TaskListHolidayResponseModel>> GetHolidays(HolidayRequestModel holidaysRequest)
{
var result = new ListHolidayResponseModel>();
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.DeserializeListHolidayResponseModel>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.EmptyHolidayResponseModel>().ToList();
}
return result;
}
}
再次運(yùn)行應(yīng)用程序,并提供國(guó)家代碼和年份值,您應(yīng)該能夠看到以下公共假期列表。

到此這篇關(guān)于Blazor Server 應(yīng)用程序中進(jìn)行 HTTP 請(qǐng)求的文章就介紹到這了,更多相關(guān)Blazor Server內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- [Asp.Net Core]用Blazor Server Side實(shí)現(xiàn)圖片驗(yàn)證碼
- [Asp.Net Core] 淺談Blazor Server Side
- Ant Design Blazor 組件庫的路由復(fù)用多標(biāo)簽頁功能
- HTTP中header頭部信息詳解
- Golang簡(jiǎn)單實(shí)現(xiàn)http的server端和client端
- IOS利用CocoaHttpServer搭建手機(jī)本地服務(wù)器
- Golang實(shí)現(xiàn)http server提供壓縮文件下載功能
- 在Golang中使用http.FileServer返回靜態(tài)文件的操作
- 基于http.server搭建局域網(wǎng)服務(wù)器過程解析
- golang的httpserver優(yōu)雅重啟方法詳解