c# - 为什么我在 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();
}
}
}
解决方案
如果您可以向我们展示您的 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)
};
});
}
推荐阅读
- flutter-web - 如何在 Flutter web 中截取小部件的屏幕截图
- google-app-engine - Google App Engine 自定义域不会从 DNS 中释放我的域名
- java - 如何使用 REST API 调用将非常大的 postgres 数据库表同步到 Web 软件?
- mongodb - Meteor 和 GroundDB:按 id 查找不返回任何条目
- javascript - 如何修复 Vue 警告:组件渲染函数中可能存在无限更新循环
- python - subprocess.check_output() : 设置 parm executable='/bin/bash' 时找不到 bash 命令
- r - 基于 2 个语句的 R(dplyr 包) 中的计数组
- c - 在 C 中写入来自文件的处理队列
- react-native - React-Native 应用程序和阿拉伯语电话设置布局被破坏
- visual-studio-2010 - 将图片框卡在另一个图片框内