为什么我在blazor中收到一个http客户端错误?

时间:2019-12-06 19:45:48

标签: c# asp.net-core blazor

在尝试导航到Blazor应用程序的登录页面时,我不断收到错误消息。我认为错误是从那里来的。我已经在程序中安装了HTTP客户端程序包。并在“启动”中提供了参考。

“没有类型为'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();
    }
}
}

1 个答案:

答案 0 :(得分:2)

如果可以向我们展示您的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)
        };
    });
}