以下是您可以如何做到这一点。
1)创建新的 Blazor 服务器应用程序。
2)向应用程序的服务集合添加一些额外的配置。
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddControllersWithViews();
services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/"));
}
上面代码的唯一区别是:
services.AddControllersWithViews();
// You should change the URI based on your project's needs.
// It's best to get the URI from appsettings.json.
services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/"));
3)按如下方式配置应用程序的端点:
app.UseEndpoints(endpoints =>
{
// This is the line you need to add
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
4)在 Blazor 页面中,您可以使用以下任一选项来访问 API:
- 使用 HttpFactory。
- 创建您自己的 HTTP 客户端。
选项 1:如果您决定使用 HttpFactory,您应该在页面顶部添加以下代码:@inject IHttpClientFactory ClientFactory
在你的函数内部按如下方式使用它:
var clientlocal = ClientFactory.CreateClient("LocalApi");
var res = await clientlocal.GetStringAsync("api/values/5");
当然,您还需要更改您的函数签名:async Task RetrieveGet()
选项 2:如果您选择创建自己的 HTTP 客户端,则需要按如下方式调用 API:
HttpClient Http = new HttpClient();
string baseUrl = "https://localhost:44333/";
var temp2 = await Http.GetStringAsync($"{baseUrl}api/values/5");
当然,您需要更改您的函数签名:async Task RetrieveGet()
Here are screenshots for either approach. Note the same URL:
The app now hits your breakpoint, as expected:
And here is the return result:
你有它。如果您有任何疑问,请告诉我。