在ASP.NET Core 2.2中,如果认证不起作用,以下是一些可能的解决方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
// 其他服务配置...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// 其他中间件配置...
app.UseAuthentication();
// 其他中间件配置...
}
[Authorize]
public class HomeController : Controller
{
// ...
}
public async Task Login(LoginModel model)
{
// 验证用户凭据...
// 设置用户身份验证Cookie
var claims = new List
{
new Claim(ClaimTypes.Name, model.Username)
// 其他声明...
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return RedirectToAction("Index", "Home");
}
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
// 其他服务配置...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// 其他中间件配置...
app.UseAuthentication();
// 其他中间件配置...
}
这些解决方法应该能够解决ASP.NET Core 2.2中认证不起作用的问题。如果问题仍然存在,请检查日志以查看是否有其他错误消息,并尝试进一步调试。