【问题标题】:Why am i getting a http client error in blazor?为什么我在 blazor 中收到 http 客户端错误?
【发布时间】:2019-12-06 19:45:48
【问题描述】:

我在尝试导航到 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();
    }
}
}

【问题讨论】:

  • 我猜你将 HttpClient 注入到你的类构造函数中?
  • 你能显示你的 startup.cs 文件吗?
  • 您好 R.Alfred,我知道您是新用户,您的问题已被投票结束,我不希望您对 StackOverflow 感到灰心。请查看本指南以提问:stackoverflow.com/help/how-to-ask 问题应该是具体的,并尽可能显示简短的相关代码块。无论如何,我尽我所能发布一个希望有用的答案
  • 编辑很有帮助,但请注意您标记了[blazor-clientside],这是错误的 - 您使用的是服务器端。这种差异在这里至关重要。
  • 是的,这是我的错误。在服务器端 blazor 上,我应该创建自己的 HttpClient 实例,而不是仅在我的组件中使用 @inject HttpClient 。我收到这个错误是因为 DI 中没有一个,并且注入 HttpClient 没有添加一个。

标签: c# asp.net-core blazor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 2021-12-09
    • 2022-12-19
    • 2020-07-11
    • 1970-01-01
    • 2014-03-15
    • 2021-06-24
    • 2020-01-30
    相关资源
    最近更新 更多