ASP.NET CORE SignInAsync需要浏览器刷新

时间:2016-09-01 19:51:27

标签: asp.net-mvc

我正在构建一个使用Windows身份验证的Intranet站点,但使用Entity Framework存储授权声明。没有用户登录。如果浏览器关闭(cookie已删除)并且应用程序重新启动(CNTRL F5),Home / Index控制器将检查用户WindowsIdentity是否已注册,并且应该登录用户。

    public async Task<IActionResult> Index()
    {
        string userWin = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
        var user = await _userManager.FindByNameAsync(userWin);
        if (user != null)
        {
            await _signInManager.SignInAsync(user, isPersistent: false);
            string userHTTP = HttpContext.User.Identity.Name;
            ViewData["Message"] = $"Registered User: {user} and HTTPUser: {userHTTP} is registered for this site";
        }
        else
            ViewData["Message"] = "Please contact admin to register for this website";

        return View();
    }

第一次运行时,userHTTP为null,并且不执行需要用户登录的视图html。如果刷新浏览器,则一切正常。为什么登录和HTTPContext需要刷新?

1 个答案:

答案 0 :(得分:1)

此行为是&#34;按设计&#34;。从文档: ASP.NET Core提供cookie中间件,将用户主体序列化为加密cookie,然后在后续请求中验证cookie,重新创建主体并将其分配给HttpContext上的User属性 。 由于这是一个具有Windows身份验证的Intranet站点,因此站点注册用户将获得一个没有登录重定向的登录用户视图。 Index函数被重定向到自身以模拟后续请求:

            string userHTTP = User.Identity.Name;
            if (userHTTP == null)
            { //will be null on first request with new cookie.  Rerun the request.
                await _signInManager.SignInAsync(user, isPersistent: false);
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }
            else
                ViewData["Message"] = $"Registered User: {user} and HTTPUser: {userHTTP} is registered for this site";

我是这一切的新手。如果未经修改,请添加评论。

相关问题