【发布时间】:2021-10-03 03:34:05
【问题描述】:
我在使用 Blazor 服务器应用时遇到问题 我在 startup.cs 中使用 HttpClient,我想在 api 请求之前添加令牌作为标头。
[Inject]
public FKSERVICES fKSERVICES { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSingleton<FKSERVICES>();
services.AddScoped<IAuthenticationService, AuthenticationService>();
services.AddHttpClient<IHttpService, HttpService>();
services.AddHttpClient<ILocalStorageService, LocalStorageService>();
services.AddHttpClient<ICategoryService, CategoryService>(client => {
client.BaseAddress = new Uri("https://localhost:5001/");
string tokenVal = fKSERVICES.GetToken();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", tokenVal);
});
}
我尝试了很多方法来做到这一点,但即使我用简单的方法创建新类时,我总是得到同样的错误,同样的错误来了 这是我创建的 FKSERVICES 服务,用于测试我是否可以从其他类中获得价值
public class FKSERVICES
{
public FKSERVICES()
{
}
public string GetToken()
{
return "";
}
}
这是错误 enter image description here
请帮帮我
【问题讨论】:
-
您确定
[Inject] public FKSERVICES fKSERVICES不为空吗? -
您需要为接受
IServiceProvider的.AddHttpClient使用不同的重载,然后从中解析FKServices。 -
@abdusco thnx 你能给我举个例子吗?
标签: c# asp.net asp.net-core blazor blazor-server-side