【问题标题】:blazor server app Auth problem with adding tokenblazor 服务器应用程序添加令牌的身份验证问题
【发布时间】: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


【解决方案1】:

如果你在AddHttpClient方法中设置断点并检查fKSERVICES,你可以看到它是Null,因为你没有创建一个实例或为它设置值。

要获取令牌,您可以修改 AddHttpClient 方法如下:

services.AddHttpClient<ICategoryService, CategoryService>(client =>
{
    #pragma warning disable ASP0000 // Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'
    var sp = services.BuildServiceProvider();
    #pragma warning restore ASP0000 // Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'
    var kservice = sp.GetRequiredService<FKSERVICES>();
    client.BaseAddress = new Uri("https://localhost:5001/");
    string tokenVal = kservice.GetToken();
    
   // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", tokenVal);

});

结果如下(在FKSERVICES.GetToken方法中,我会返回一个字符串:“FKSERVICES Token”):

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 2021-01-26
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2021-04-26
    • 2012-06-05
    相关资源
    最近更新 更多