c# - 如何使用带有特定数据的 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 ?
这是我的饼干;
- Kim Dağıtıcı Ad Değer
- Furkan 地方当局http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier c557cfef-fa95-4b5a-8dce-fe01bfa94737
- 列表项 Furkan LOCAL AUTHORITY http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
4.Furkan内部用户ID 53
解决方案
第一:在你想读取它的值之前,我看不到你在 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
}
推荐阅读
- javascript - 使用 Session 存储来存储弹窗是否已经显示
- node.js - Webpack Babel NodeJS 错误:必须使用导入来加载 ES 模块
- reactjs - 有没有办法减少这个带宽?
- python - 我需要从查询中将“一对多”数据从 python 插入 sql
- python - torchvision.transforms.RandomRotation 填充参数不起作用
- twilio - Twilio 可以处理入站组彩信吗
- c++ - 移动链接到构造函数的方法的语义
- html - 更改角度材料自动完成的样式
- laravel - 如何从 laravel 中的关系表中获取计数?
- amazon-web-services - Glue ML 转换 ---java.lang.IllegalArgumentException Unrecognized scheme null; 预期 s3、s3n 或 s3a