如何在ASP.NET MVC Core 2.0中维护会话值

时间:2019-01-17 19:45:55

标签: c# asp.net-core-mvc

如何在mvc core 2.0中使用会话,例如在mvc 5和webforms中使用。 “ Session [” bla Bla“]”,以及如何使用存储在会话中的userId在项目中的其他控制器中。 这是我的登录代码:

 public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
      //  string userId = "";
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var username = await _userManager.FindByEmailAsync(model.Email);
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(username.UserName, model.Password, false,  false);
            if (result.Succeeded)
            {


                _httpContext.HttpContext.Session.SetString("UserId",username.Id);
                            _logger.LogInformation("User logged in.");
                return RedirectToLocal(returnUrl);
                //return RedirectToAction("Index");
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User account locked out.");
                return RedirectToAction(nameof(Lockout));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

在启动部分 在ConfigureServices方法中

       services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            options.Cookie.Name = "FSession";
        });

并配置方法

app.UseSession();

1 个答案:

答案 0 :(得分:3)

当您像这样设置会话密钥UserId时:

HttpContext.Session.SetString("UserId", username.Id);

您可以像这样在另一个控制器中访问它:

public IActionResult DoStuffWithUserId()
{
    string userid = HttpContext.Session.GetString("UserId");

    // do stuff with the userid now...

    return View();
}

但是,通过使用

,确保其他控制器的代码文件包含对Microsoft.AspNetCore.Http的引用。
using Microsoft.AspNetCore.Http;

访问扩展方法GetString()

请看here,以获得更详细的示例。