C# 读取/写入 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11010542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:06:05  来源:igfitidea点击:

Reading/Writing Cookies

c#asp.netcookies

提问by DeadManWalking

I joined this site today hoping someone would be kind enough to explain to me what i'm doing wrong with cookies in ASP.NET. I'm still learning so apoligies if my question is too basic, but i cannot find the answer on google. Every answer i find shows the code I already have.

我今天加入了这个网站,希望有人能够向我解释我在 ASP.NET 中做错了什么。如果我的问题太基本,我仍在学习如此apoligies,但我无法在谷歌上找到答案。我找到的每个答案都显示了我已经拥有的代码。

I am experimenting with creating and reading cookies, i have put this code in my applications constructor. this is how i try to initialize my cookie and add it to the browser.

我正在尝试创建和读取 cookie,我已将此代码放入我的应用程序构造函数中。这就是我尝试初始化我的 cookie 并将其添加到浏览器的方式。

global.asax.cs

global.asax.cs

    public MyApplication()
    {
        myCookie = new HttpCookie("UserSettings");
        myCookie.Value = "nl";
        myCookie.Expires = DateTime.Now.AddDays(1d);
        Response.Cookies.Add(myCookie);
    }

a method in HomeController.cs (trying to read the cookie)

HomeController.cs 中的一个方法(尝试读取 cookie)

    public void setLang(string lang)
    {
        HttpCookie myCookie = Request.Cookies["UserSettings"];
        myCookie.Value = lang;
        //rest of method

I am getting an error at Response.Cookies.Add(myCookie); [HttpException (0x80004005): Response is not available in this context.]

我在 Response.Cookies.Add(myCookie) 处遇到错误;[HttpException (0x80004005): 响应在此上下文中不可用。]

My thought is that i might have forgot to import a namespace or something, but nothing i do seems to fix this error, can anyone point me in the right direction?

我的想法是我可能忘记导入命名空间或其他东西,但我似乎没有做任何事情来解决这个错误,有人能指出我正确的方向吗?

采纳答案by Jaimal Chohan

You can't use the Global.asax constructor to add a cookie to the Response because the Global.asax constructor is called before the application starts processing the HTTP request.

您不能使用 Global.asax 构造函数向响应添加 cookie,因为 Global.asax 构造函数在应用程序开始处理 HTTP 请求之前被调用。

Move your code from the Global.asax constructor to the Application_BeginRequestmethod:

将您的代码从 Global.asax 构造函数移动到Application_BeginRequest方法:

public void Application_BeginRequest()
{
    myCookie = new HttpCookie("UserSettings");
    myCookie.Value = "nl";
    myCookie.Expires = DateTime.Now.AddDays(1d);
    Response.Cookies.Add(myCookie);
}

The Global.asax has a number of different events that are fired, you just chose wrongly.

Global.asax 有许多不同的事件被触发,你只是选择错误。

  • Application_Init: Fires when the application initializes for the first time.
  • Application_Start: Fires the first time an application starts.
  • Session_Start: Fires the first time when a user's session is started.
  • Application_BeginRequest: Fires each time a new request comes in.
  • Application_EndRequest: Fires when the request ends.
  • Application_AuthenticateRequest: Indicates that a request is ready to be authenticated.
  • Application_Error: Fires when an unhandled error occurs within the application.
  • Session_End: Fires whenever a single user Session ends or times out.
  • Application_End: Fires when the application ends or times out (Typically used for application cleanup logic).
  • Application_Init: 当应用程序第一次初始化时触发。
  • Application_Start: 应用程序第一次启动时触发。
  • Session_Start:当用户会话开始时第一次触发。
  • Application_BeginRequest: 每次收到新请求时触发。
  • Application_EndRequest: 当请求结束时触发。
  • Application_AuthenticateRequest:表示请求已准备好进行身份验证。
  • Application_Error:当应用程序中发生未处理的错误时触发。
  • Session_End:每当单个用户会话结束或超时时触发。
  • Application_End:当应用程序结束或超时时触发(通常用于应用程序清理逻辑)。

(from http://en.wikipedia.org/wiki/Global.asax)

(来自http://en.wikipedia.org/wiki/Global.asax

回答by jishan siddique

cookies is a small piece of information stored on the client machine. This file is located on client machines.Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called Systen.Web.HttpCookie before we use cookie.

cookie 是存储在客户端计算机上的一小段信息。该文件位于客户端机器上。它用于在客户端机器上存储用户首选项信息,如用户名、密码、城市和电话号码等。在使用 cookie 之前,我们需要导入名为 Systen.Web.HttpCookie 的命名空间。

Type of Cookies? Persist Cookie - A cookie has not have expired time Which is called as Persist Cookie

Cookie 的类型?Persist Cookie - 一个 cookie 没有过期,称为 Persist Cookie

Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie 

How to create a cookie?

如何创建cookie?

Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie

在 Response 对象或 HttpCookie 的帮助下,在 Asp.Net 中创建 cookie 真的很容易

    HttpCookie userInfo = new HttpCookie("userInfo");
    userInfo["UserName"] = "Jishan siddique";
    userInfo["UserColor"] = "Black";
    userInfo.Expires.Add(new TimeSpan(0, 1, 0));
    Response.Cookies.Add(userInfo);

回答by jishan siddique

Cookie's common property:

Cookie 的共同属性:

1.Domain => Which is used to associate cookies to domain.

2.Secure  => We can enable secure cookie to set true(HTTPs).

3.Value    => We can manipulate individual cookie.

4.Values  => We can manipulate cookies with key/value pair.

5.Expires => Which is used to set expire date for the cookies. 

Advantages of Cookie:

饼干的优点:

1.Its clear text so user can able to read it.

2.We can store user preference information on the client machine.

3.Its easy way to maintain.

4.Fast accessing.

Disadvantages of Cookie

饼干的缺点

1.If user clear cookie information we can't get it back.

2.No security.

3.Each request will have cookie information with page. 

How to clear the cookie information?

如何清除cookie信息?

1.we can clear cookie information from client machine on cookie folder

1.我们可以清除客户端机器cookie文件夹中的cookie信息

2.To set expires to cookie object userInfo.Expires = DateTime.Now.AddHours(1); It will clear the cookie with one hour duration

2.将过期时间设置为cookie对象userInfo.Expires = DateTime.Now.AddHours(1); 它将以一小时的时间清除 cookie

回答by jishan siddique

You can use predefined namespace in .Net. Like this:

您可以在 .Net 中使用预定义的命名空间。像这样:

System.Web.HttpContext.Current.Response.addCookie(cookieobject);