【发布时间】:2020-12-12 16:26:34
【问题描述】:
我是 ASP.NET 的新手,正在尝试添加新的 cookie。我正在使用 ASP.NET 版本 3.1.401,在我的 homecontroller 文件中,我试图遵循:How to create persistent cookies in asp.net?。我有一个 using-statement 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 模式中我应该在哪里进行?
【问题讨论】:
-
您的项目中是否定义了名为
HttpCookie的自定义类型?从错误消息中,您引用的是HomeController.HttpCookie而不是System.Web.HttpCookie -
没有“ASP.NET 版本 3.1.401” - 您真的是指 ASP.NET Core v3.1.401 吗?如果是这样 - 请澄清!您需要精确标记产品和版本!
-
你可以试试这个:HttpContext.Request.Cookies.Values["userid"]= "SomeValue";
-
这并没有解决我在
HttpCookie myCookie = new HttpCookie("myCookie");这一行遇到的初始错误,所以当我尝试时仍然有错误
标签: c# asp.net-core