我Angular 14在前端和.NET 7后端都使用過。當我重繪 頁面時,出現此錯誤:
決議 https://localhost:6001/Account/Login?ReturnUrl=/api/account/currentuser 時出現 HTTP 失敗”
我怎么解決這個問題?
在后端:
我認為問題的原因在于這行代碼:
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ShopDbContext>();
因為如果我洗掉
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>() .AddRoles() .AddEntityFrameworkStores();
并寫這個代替它
builder.AddEntityFrameworkStores();
并從中洗掉這部分代碼GetCurrentUser()
var role = (await _userManager.GetRolesAsync(user)).FirstOrDefault(); if (role == null) { role = Role.Standard.ToString("f"); 等待 _userManager.AddToRoleAsync(用戶,角色);}
該應用程式有效但沒有角色功能。
添加身份服務方法:
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
{
var builder = services.AddIdentityCore<ApplicationUser>();
builder = new IdentityBuilder(builder.UserType, builder.Services);
builder.AddSignInManager<SignInManager<ApplicationUser>>();
// I think that the cause of the problem is in this line of code.
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ShopDbContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
ValidIssuer = config["Token:Issuer"],
ValidateIssuer = true,
ValidateAudience = false
};
});
return services;
}
獲取當前用戶方法:
[Authorize]
[HttpGet]
public async Task<ActionResult<UserDto>> GetCurrentUser()
{
var user = await _userManager.FindByEmailFromClaimsPrinciple(User);
if (user == null)
{
return null;
}
var role = (await _userManager.GetRolesAsync(user)).FirstOrDefault();
if (role == null)
{
role = Role.Standard.ToString("f");
await _userManager.AddToRoleAsync(user, role);
}
return new UserDto
{
Email = user.Email,
Token = _tokenService.CreateToken(user),
DisplayName = user.DisplayName,
Role = role,
};
}
應用角色:
public class ApplicationRole : IdentityRole<int>
{
public ApplicationRole() : base()
{
}
public ApplicationRole(string name) : base(name)
{
Name = name;
}
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
public virtual ICollection<ApplicationRoleClaim> RoleClaims { get; set; }
}
在前端:
loadCurrentUser(token: string | null): Observable<void> {
if (token === null) {
this.currentUserSource.next(null);
return of();
}
let headers = new HttpHeaders();
headers = headers.set('Authorization', `Bearer ${token}`);
return this.http.get(this.baseUrl 'account', { headers }).pipe(
map((user: any) => {
console.log("user = ", user);
if (user) {
localStorage.setItem('token', user.token);
this.currentUserSource.next(user);
}
})
);
}

uj5u.com熱心網友回復:
我添加builder.AddRoles<ApplicationRole>()并洗掉了builder.Services.AddIdentity.
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
{
var builder = services.AddIdentityCore<ApplicationUser>();
builder = new IdentityBuilder(builder.UserType, builder.Services);
builder.AddSignInManager<SignInManager<ApplicationUser>>();
builder.AddRoles<ApplicationRole>();
builder.AddEntityFrameworkStores<ShopDbContext>();
// rest of the code ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537636.html
