首页 > 解决方案 > 如何使用带有特定数据的 httpcookie?

问题描述

我有一个 cookie,但我需要 UserID 中的 cookie,

我写在 cookie 用户 ID 中,我需要访问这个用户 ID 的每个页面。

我可以访问我的 cookie “响应”,但这个数据非常大,我需要在用户 ID 中响应。

这是我的代码:

public IActionResult Index()
    {
        string cookie = HttpContext.Request.Cookies["response"];
        ViewData["Cookie"] = cookie;
        return View();
    }

我正在搜索这个主题并找到方法,

这是新代码,但它不起作用。

            var computername = HttpContext.Request.Cookies["response"].Value;

这是找到其他方法,但它不起作用。

      int User_id;
        HttpCookie reqCookies = HttpContext.Request.Cookies["response"];
        if (reqCookies != null)
        {
            User_id = reqCookies["UserID"].ToString();
            ViewData["Cookie"] = User_id;

        }

如何访问 UserID 53 ?

这是我的饼干;

  1. Kim Dağıtıcı Ad Değer
  2. Furkan 地方当局http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier c557cfef-fa95-4b5a-8dce-fe01bfa94737
  3. 列表项 Furkan LOCAL AUTHORITY http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name

4.Furkan内部用户ID 53

标签: c#asp.net-mvccookies

解决方案


第一:在你想读取它的值之前,我看不到你在 Cookie 中保存数据的位置

第二:将cookie另存为对象,然后在接收后再次将其投射到该对象并选择您想要的属性

我在示例中使用UserDTO作为保存用户数据的用户对象

登录后

public IActionResult Login(UserDTO user)
{
    ...

    // after validating and login success
    var cookie = new HttpCookie("response", user);
    cookie.Expires = DateTime.Now.AddDays(30);
    Response.Cookies.Add(cookie); // use here Response.Cookies not Request.Cookies
    ...

    return View();
}

public IActionResult Index()
{
    var cookie = HttpContext.Request.Cookies["response"] as UserDTO; // must be the same type when set its value
    ViewData["Cookie"] = cookie;
    return View();
}

并在视图中

var computername = HttpContext.Request.Cookies["response"].Value as UserDTO; // to prevent casting exception .. will return null if cast faild
if(computername != null) 
{
    computername.Name;// will return Kim 
    computername.UserId;// will return 53 
}

推荐阅读