0
    namespace AspWebAppTest.Controllers
    {
    public class AccountController : Controller
    {
    
    public IActionResult Login()
    {
        return View();
    }
    
    [HttpGet]
    public IActionResult Login(string userName, string password)
    {
        if (!string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password))
        {
            return RedirectToAction("Login");
        }

        
        ClaimsIdentity identity = null;
        bool isAuthenticated = false;

        if (userName == "Admin" && password == "pass")
        {

           
            identity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Role, "Admin")
            }, CookieAuthenticationDefaults.AuthenticationScheme);

            isAuthenticated = true;
        }
        if (isAuthenticated)
        {
            var principal = new ClaimsPrincipal(identity);

            var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

            return RedirectToAction("Mapping","Setting", "Home");
        }

        return View();
    }
    public IActionResult Logout()
    {
        var login = HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Login");
    }

}

}

我的标签(映射和配置)有这个 Cookie 身份验证控制器。一旦用户输入了正确的密码和用户名,我正在使用 RedirectToAction() 方法将我的返回视图重定向到访问映射和配置选项卡。我的问题是,输入密码和用户名后,什么也没有发生。我使用了错误的方法吗?

这是我的startup.cs

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

在此处输入图像描述

4

1 回答 1

0

SignInAsync方法返回一个Task将在登录操作成功时完成的操作。

您的代码没有awaitthis Task,因此您在用户通过身份验证之前发送重定向响应。

使您的操作async和方法await的结果Sign[In|Out]Async

[HttpGet]
public async Task<IActionResult> Login(string userName, string password)
{
    ...
    if (isAuthenticated)
    {
        var principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

        return RedirectToAction("Mapping", "Setting", "Home");
    }

    return View();
}

public async Task<IActionResult) Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return RedirectToAction("Login");
}
于 2022-02-03T17:09:41.777 回答