c# - 使用 ASP.NET 核心添加新的持久性 cookie
问题描述
我是 ASP.NET 的新手,正在尝试添加一个新的 cookie。我正在使用 ASP.NET 版本 3.1.401,并且在我的 homecontroller 文件中我试图遵循这个:如何在 asp.net 中创建持久性 cookie?. 我有一个 using 语句using System.Web
,在我的 homecontroller 类中,我有一个方法,如下所示:
public IActionResult Index()
{
@ViewData["timezone"] = Convert.ToString(TimeZoneController.showTimeZone());
@ViewData["ip"] = IPController.getIP();
//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");
//Add key-values in the cookie
myCookie.Values.Add("userid", "new_user");
//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);
//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);
return View();
}
而且我不断收到以下错误:
CS1729: 'HomeController.HttpCookie' does not contain a constructor that takes 1 arguments
和
CS1061: 'HomeController.HttpCookie' does not contain a definition for 'Values' and no accessible extension method 'Values' accepting a first argument of type 'HomeController.HttpCookie' could be found (are you missing a using directive or an assembly reference?)
如何获取和设置 cookie 以及在 MVC 模式中应该在哪里进行?
解决方案
我意识到我的错误是我在 macos 上开发,因此我使用的是 ASP.NET 核心而不是 ASP.NET。这是一个愚蠢的错误,但我相信很多初学者都会做到。这是一个关于如何在使用 ASP.NET 核心时设置 cookie的链接。
推荐阅读
- swift - 是否可以使用 switch 方法将 2 个字符串匹配在一起?
- cloud - 强制应用程序仅在 PCF 中的一个实例中运行
- binary - 反编译 8051 二进制,从 EEPROM 读取
- r - R如何将列表转换为向量,以及为什么要使用列表
- android-fragments - Exo Player 在为容器片段设置动画时变黑,如何解决?
- c# - 我托管的 Azure 管道失败:rcz discover exited with code -2147450730
- winapi - winapi - 如何从资源文件中获取控制 RECT 结构
- javascript - 使用 Node.js 从 MySQL 返回值
- r - 我的带有对数变量的面板线性回归在非有限值上返回错误,但在零值或负值上没有对数
- ruby - 我不能打破一个循环