首页 > 解决方案 > 为什么我在 blazor 中收到 http 客户端错误?

问题描述

在尝试导航到 Blazor 应用程序的登录页面时,我不断收到错误消息。我认为错误来自那里。我已经在程序中安装了 HTTP 客户端包。以及在 Startup 中做了参考。

“没有‘System.Net.Http.HttpClient’类型的注册服务。”

namespace GLI
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddTokenAuthenticationStateProvider();
       services.AddHttpClient();
       services.AddSingleton<WeatherForecastService>();

    var secretkey = Encoding.ASCII.GetBytes(ClsGlobal.Secret);
     //Configuring JWToken Authentication

    services.AddAuthentication(auth =>
        {
            auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
      .AddJwtBearer(token =>
      {
    token.RequireHttpsMetadata = false;
    token.SaveToken = true;
    token.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(secretkey),
        ValidateIssuer = true,
        //ValidIssuer = "http://localhost:45092/",
        ValidateAudience = true,
        ValidAudience = "https://localhost:44358/",
        RequireExpirationTime = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
});
    }




@code {
RazorComponents.MaterialDesign.MdcDialog dialog;
LoginCredentials credentials = new LoginCredentials();
bool lastSigninFailed;

public Task SignIn()
  => dialog.ShowAsync();

public Task SignOut()
    => AuthStateProvider.SetTokenAsync(null);
async Task SubmitCredentials()
{
    var result = await Http.PostJsonAsync<LoginResult>("api/user/login", credentials);
    lastSigninFailed = result.Token == null;
    if (!lastSigninFailed)
    {
        // Success! Store token in underlying auth state service
        await AuthStateProvider.SetTokenAsync(result.Token);

        // Reset UI state
        await dialog.HideAsync();
        credentials = new LoginCredentials();
    }
}
}

标签: c#asp.net-coreblazor

解决方案


如果您可以向我们展示您的 startup.cs 文件会很有帮助,但您可以尝试将其添加到您的 startup.cs 以注册 HttpClient 服务

if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
{
    services.AddScoped<HttpClient>(s =>
    {
        var uriHelper = s.GetRequiredService<NavigationManager>();
        return new HttpClient
        {
            BaseAddress = new Uri(uriHelper.BaseUri)
        };
    });
}

推荐阅读