【问题标题】:Add a new persistent cookie using ASP.NET core使用 ASP.NET 核心添加新的持久性 cookie
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你试过了吗:

            //Add key-values in the cookie
            myCookie.Values["userid"] = "new_user";
    

    应该可以。还要确保您使用的是来自System.WebHttpCookie

    【讨论】:

    • 在这种情况下,我收到以下错误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?)
    • 好的。试试System.Web.HttpCookie myCookie = new System.Web.HttpCookie("myCookie");
    • 然后我收到以下错误CS0234: The type or namespace name 'HttpCookie' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)
    • 关闭视觉工作室并重新打开它。之后进行干净的构建
    猜你喜欢
    • 2018-03-01
    • 2017-09-08
    • 2020-06-19
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2011-01-25
    • 2020-04-20
    相关资源
    最近更新 更多