嗨,我嘗試使用 asp.net core mvc 創建專案。我創建了一些控制器和用戶身份 3.1 以添加管理用戶并向他們添加角色。我創建 2 個角色(普通、管理員),例如,我只希望普通用戶訪問 My AccountController。注冊后用戶的默認角色也是正常的。但是當這種型別的用戶登錄并嘗試打開帳戶時,他們會重定向到登錄頁面。我怎樣才能解決這個問題 ?
我臨時更改所有密碼選項 false 以更快地創建用戶測驗。下面的代碼是我從啟動開始的所有配置。
[Authorize(Roles = "Normal")]
public class AccountController : Controller
{
public IActionResult Index()
{
return View("Account");
}
}
enter code| services.AddDbContext<DataAcessLayer.DB>(s => s.UseSqlServer(Configuration.GetConnectionString("CON1")) );
services.AddIdentity<User, IdentityRole>(option =>
{
option.Password.RequireDigit = false;
option.Password.RequireLowercase = false;
option.Password.RequireUppercase = false;
option.Password.RequireNonAlphanumeric = false;
option.Password.RequiredLength = 5;
option.SignIn.RequireConfirmedPhoneNumber = false;
option.SignIn.RequireConfirmedAccount = false;
option.SignIn.RequireConfirmedEmail = false;
})
.AddUserManager<UserManager<User>>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<DataAcessLayer.DB>();
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Sign/404";
options.Cookie.Name = "WebAppIdentityCookie";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.LoginPath = "/Sign/SignIn";
options.SlidingExpiration = true;
});
這是我的登錄代碼:
[HttpPost]
public async Task<IActionResult> login(Models.UserModel usermodel)
{
var user = await userManager.FindByNameAsync(usermodel.UserName);
if (user == null)
{
ModelState.AddModelError("", "??? ?????? ?? ??? ???? ?????? ???.");
return View("SignIn", usermodel);
}
var SignInResult = await signInManager.PasswordSignInAsync(user, usermodel.Password, true, true);
if (SignInResult.Succeeded)
{
return RedirectToAction("Index", "Account");
}
else
{
ModelState.AddModelError("", "??? ?????? ?? ??? ???? ?????? ???.");
return View("SignIn", usermodel);
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
uj5u.com熱心網友回復:
嘗試改變
app.UseAuthorization();
app.UseAuthentication();
至
app.UseAuthentication();
app.UseAuthorization()
閱讀這篇文章:
Asp.net 核心中間件
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/508225.html
標籤:asp.net-mvc 模型视图控制器 asp.net 身份 用户角色
上一篇:根據傳入值更改文本
