要在Blazor WebAssembly中调用受保护的Web API方法并传递令牌,可以按照以下步骤进行操作:
Program.cs
文件中,添加using
语句using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
,并在CreateHostBuilder
方法中调用UseBlazorWebAssemblyAuthentication()
方法。using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("app");
builder.Services.AddHttpClient("API", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler();
// 添加认证服务配置
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("oidc", options.ProviderOptions);
});
await builder.Build().RunAsync();
}
}
Services
文件夹中创建一个名为ApiService.cs
的类,用于封装调用Web API的方法。using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
public class ApiService
{
private readonly HttpClient _httpClient;
private readonly IAccessTokenProvider _accessTokenProvider;
public ApiService(HttpClient httpClient, IAccessTokenProvider accessTokenProvider)
{
_httpClient = httpClient;
_accessTokenProvider = accessTokenProvider;
}
public async Task GetProtectedData()
{
var accessToken = await _accessTokenProvider.RequestAccessToken();
// 将令牌添加到请求头中
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var data = await _httpClient.GetFromJsonAsync("api/protected");
return data;
}
}
Program.cs
文件的ConfigureServices
方法中,将ApiService
类注册到DI容器中。using Microsoft.Extensions.DependencyInjection;
public class Program
{
public static async Task Main(string[] args)
{
// ...
builder.Services.AddScoped();
// ...
}
}
ApiService
服务,并调用其中的方法。@inject ApiService ApiService
@code {
private string protectedData;
private async Task GetProtectedData()
{
protectedData = await ApiService.GetProtectedData();
}
}
通过以上步骤,你就可以在Blazor WebAssembly中调用受保护的Web API方法并传递令牌了。请确保你的Web API已经配置了正确的身份验证和授权。