如何将httpcookie与特定数据一起使用?

时间:2020-02-03 19:16:06

标签: c# asp.net-mvc cookies

我有一个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?

这是我的cookie;

  1. KimDağıtıcıAdDeğer
  2. 富坎当地政府http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier c557cfef-fa95-4b5a-8dce-fe01bfa94737
  3. 列出项目Furkan本地授权http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name

4.Furkan内部用户ID 53

1 个答案:

答案 0 :(得分:0)

第一:在您想读取数据值之前,我看不到将数据保存在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 
}