下面是一个使用身份验证进行 Web API 调用的 Blazor Server 的示例代码:
首先,确保在 Blazor Server 项目中启用了身份验证。
在 Startup.cs
文件中的 ConfigureServices
方法中添加以下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://example.com"; // 替换为你的身份验证提供者的 URL
options.ClientId = "your-client-id"; // 替换为你的客户端 ID
options.ClientSecret = "your-client-secret"; // 替换为你的客户端密钥
});
然后,在 Startup.cs
文件中的 Configure
方法中添加以下代码:
app.UseAuthentication();
app.UseAuthorization();
接下来,创建一个名为 MyApiService.cs
的类,用于处理 API 调用。在该类中,注入 HttpClient
和 AuthenticationStateProvider
:
using Microsoft.AspNetCore.Components.Authorization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class MyApiService
{
private readonly HttpClient _httpClient;
private readonly AuthenticationStateProvider _authenticationStateProvider;
public MyApiService(HttpClient httpClient, AuthenticationStateProvider authenticationStateProvider)
{
_httpClient = httpClient;
_authenticationStateProvider = authenticationStateProvider;
}
public async Task GetApiData()
{
var authToken = await GetAuthToken();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var response = await _httpClient.GetAsync("https://example-api.com/data"); // 替换为你的 API URL
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
private async Task GetAuthToken()
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
var token = user.FindFirst("access_token").Value;
return token;
}
}
在 Blazor 组件中,可以使用 MyApiService
类来进行 API 调用。例如,在一个名为 FetchData.razor
的组件中进行调用:
@page "/fetchdata"
@inject MyApiService MyApiService
API Data
@if (string.IsNullOrEmpty(apiData))
{
Loading...
}
else
{
@apiData
}
@code {
private string apiData;
protected override async Task OnInitializedAsync()
{
apiData = await MyApiService.GetApiData();
}
}
在上面的示例中,MyApiService
类注入了 HttpClient
和 AuthenticationStateProvider
。在调用 API 之前,我们首先获取用户的访问令牌,并将其添加到 HttpClient
的默认请求头中。然后,我们使用 HttpClient
发起 API 请求,并返回结果。
请记得将示例代码中的 URL、客户端 ID 和客户端密钥替换为你自己的值。此外,你还可以根据需要修改代码以适应你的应用程序的逻辑和需求。