【问题标题】:How can use httpcookie with specific data?如何使用带有特定数据的 httpcookie?
【发布时间】:2020-02-04 12:19:58
【问题描述】:

我有一个 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 地方当局http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name

4.Furkan 内部用户ID 53

【问题讨论】:

  • 我无法理解这个问题。看起来好像您在 cookie 中有大量数据并想从中获取一些特定数据?如果是这样,我建议将您的数据分成更小的 cookie,或者使用不同的机制(例如隐藏字段)来保存您的数据。
  • 是的,是的。我正在编辑问题。这是一个不是很大的数据,我认为它更小,但我是新人,我无法解决这个问题

标签: c# asp.net-mvc cookies


【解决方案1】:

首先:在你想读取它的值之前,我看不到你在 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 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多