首页 > 解决方案 > 为每个用户身份设置会话

问题描述

View在 ASP.NET MVC 中有一个简单的页面

@HttpContext.Current.Session["User"].ToString() @DateTime.Now

我只是想以编程方式设置用户的身份,以便当我重新导航到此页面或任何其他页面时,我可以获得当前的用户身份。

此外,当导航新用户时,我需要创建一个新的用户身份。

这是控制器

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
    var pModel = new PModel
    {
        Countries = PopulateDropDown(" SELECT ... ")
    };

    HttpContext.Session["User"] = HttpContext.User.Identity.Name.ToString();
    HttpContext.Session.Timeout = 300;

    return View(pModel);
}

View如果我从台式电脑连接到应用程序,这是页面上打印的值

myDomain\myUser 22/01/2021 19:53:15

现在我尝试使用新用户从我的移动设备连接到应用程序,页面上打印的值View

myDomain\myUser2 22/01/2021 20:04:37

但是当刷新我的桌面电脑上的浏览器时,页面上打印的值View更改为

myDomain\myUser2 22/01/2021 20:08:25

用户myUser2在应用程序上替换了第一个连接的用户myUser

如果我反向移动也会发生同样的情况,即移动设备与台式电脑......

对此是否有特殊考虑?

在 ASP.NET MVC 项目中使用没有问题......对于每个用户,我都有相应的 Session 而无需替换用户......

我不明白我的 ASP.NET MVC 应用程序中的这个问题......对不起......

public static string tUser
{
    get
    {
        if (HttpContext.Current.Session["tUser"] != null)
        {
            return HttpContext.Current.Session["tUser"].ToString();
        }
        return null;
    }
    set
    {
        HttpContext.Current.Session["tUser"] = value;
    }
}

更新#1

在此处输入图像描述

更新#2

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
        System.Web.HttpContext.Current.Session["User"] = HttpContext.User.Identity.Name.ToString();
        System.Web.HttpContext.Current.Session.Timeout = 300;

    var pModel = new PModel
    {
        Countries = PopulateDropDown(" SELECT ... ")
    };

    return View(pModel);
}

标签: c#asp.net-mvcasp.net-identity

解决方案


推荐阅读