【发布时间】: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