首页 > 解决方案 > 使用 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 模式中应该在哪里进行?

标签: c#asp.net-core

解决方案


我意识到我的错误是我在 macos 上开发,因此我使用的是 ASP.NET 核心而不是 ASP.NET。这是一个愚蠢的错误,但我相信很多初学者都会做到。这是一个关于如何在使用 ASP.NET 核心时设置 cookie的链接。


推荐阅读