在 C# 中读取 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11029643/
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:10:53  来源:igfitidea点击:

Reading cookie in c#

c#cookies

提问by DeadManWalking

I want someone who visits my internationalized site to be able to change the language. I thought best way would be to store the language chosen in a cookie - so when the page loads, it can look up the preferred language in the cookie.

我希望访问我的国际化网站的人能够更改语言。我认为最好的方法是在 cookie 中存储选择的语言 - 这样当页面加载时,它可以在 cookie 中查找首选语言。

Writing the cookie is going perfect, however I keep running into errors trying to read it. As I'm new to C# im having trouble translating the errors visual studio throws at me.

编写 cookie 很完美,但是我一直在尝试读取它时遇到错误。由于我是 C# 新手,因此无法翻译 Visual Studio 向我抛出的错误。

I want the value of a cookie called 'UserSettings' in a string called lang. I'm trying like this:

我想要名为 lang 的字符串中名为“UserSettings”的 cookie 的值。我正在尝试这样:

string lang = Request.Cookies["UserSettings"].Value;

The error it throws is:

它抛出的错误是:

Object reference not set to an instance of an object

你调用的对象是空的

I'm thinking the problem has to be on the right side of the statement, since I'm initializing the string on the left side.

我认为问题必须在语句的右侧,因为我在左侧初始化字符串。

I also tried making an instance of the cookie by doing

我还尝试通过执行来制作 cookie 的实例

HttpCookie cookie = Request.Cookies["UserSettings"].Value;

but visual studio doesnt like this at all.

但是visual studio根本不喜欢这个。

What am I doing wrong? Do I have to make an instance of the Request object? Any help would be appreciated.

我究竟做错了什么?我是否必须创建 Request 对象的实例?任何帮助,将不胜感激。

I'm following different tutorials on this topic, but they all result in this same error.

我正在关注有关此主题的不同教程,但它们都会导致相同的错误。

EDIT:I've noticed I had

编辑:我注意到我有

HttpCookie cookie = Request.Cookies["UserSettings"].Value;

I changed it to:

我把它改成:

HttpCookie cookie = Request.Cookies["UserSettings"]; 

but no luck, it still didn't work.

但没有运气,它仍然没有奏效。

EDIT:this is how my cookie is made

编辑:这就是我的饼干的制作方式

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

My cookie is 100% there, im absolutly sure, i can see it in Firefox-web developer.

我的 cookie 是 100% 的,我绝对可以肯定,我可以在 Firefox-web developer 中看到它。

UPDATE: this is the exact code i'm calling now

更新:这是我现在调用的确切代码

        public string getLang()
    {
       // HttpCookie aCookie = Request.Cookies["UserSettings"];
       //  string lang = Server.HtmlEncode(aCookie.Value);
       //  if (lang != null)
       // {
       //      currentLanguage = lang;
       //  }
        return currentLanguage;
    }

this way my code compiles, if I uncomment my code then it doest (error @ first line of this method)

这样我的代码编译,如果我取消注释我的代码然后它不(错误@此方法的第一行)

回答by theedam

Can you try this?

你能试试这个吗?

HttpCookie aCookie = Request.Cookies["UserSettings"];
string lang = Server.HtmlEncode(aCookie.Value);

http://msdn.microsoft.com/en-us/library/ms178194.aspx

http://msdn.microsoft.com/en-us/library/ms178194.aspx

EDIT Does this help you? asp.net mvc can't access cookie data in base controller

编辑这对你有帮助吗? asp.net mvc 无法访问基本控制器中的 cookie 数据

回答by vikrantx

first of all check for cookie is created or not.
for this use firefox and add webdeveloper plugin
After installing webdeveloper, a toolbar appear on firefox browser, select cookies tab on it
cookies -> View Cookies information it will display all cookies with their properties.

首先检查cookie是否创建。
为此使用firefox并添加webdeveloper插件
安装webdeveloper后,firefox浏览器上会出现一个工具栏,选择cookies选项卡
cookies->查看cookies信息它将显示所有cookies及其属性。

回答by jaypeagi

It sounds like the cookie is never being set. In which case you need to check for this:

听起来 cookie 从未被设置过。在这种情况下,您需要检查:

HttpCookie aCookie = Request.Cookies["UserSettings"];
if(aCookie != null) {
     object userSettings = aCookie.Value;
} else {
     //Cookie not set.
}

To set a cookie:

要设置 cookie:

HttpCookie cookie = new HttpCookie("UserSettings");

cookie["UserSettings"] = myUserSettingsObject;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);

Here is a good article: http://www.java2s.com/Code/ASP/Session-Cookie/CreateandretrieveCookiedataC.htm

这是一篇好文章:http: //www.java2s.com/Code/ASP/Session-Cookie/CreateandretrieveCookiedataC.htm

回答by dreamafon

HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie = Request.Cookies["UserSettings"];
string lang = myCookie.Value.ToString();

回答by Jan

You create your cookie within Application_BeginRequest()and add the results to the Response. It will be created on the client side only afterthe response has been sent back.

您在其中创建 cookieApplication_BeginRequest()并将结果添加到Response. 只有响应被发回,才会客户端创建它。

But you are reading the cookie value from the Requeststate, perhaps the original request beforethe response with the cookie has been sent back to the client? At this time within the life cycle however this cookie is not contained in the Requestand thus is null.

但是您正在从Request状态中读取 cookie 值,也许在带有 cookie 的响应之前的原始请求已发送回客户端?然而,在生命周期内的这个时候,这个 cookie 不包含在 中Request,因此是null

Your client would have to send another request afterthe cookie has been created in order to make it available to the server and this makes perfect sense to me.

您的客户端必须在创建 cookie发送另一个请求才能使其对服务器可用,这对我来说非常有意义。

The reason that you can see the cookie in your web developer tools is, that the server will send the Responseback to the client. However it will not be present in the current Requeststate, unless a new request with the cookie will be sent by the client.

您可以在 Web 开发人员工具中看到 cookie 的原因是,服务器会将 cookie 发送Response回客户端。然而,它不会出现在当前Request状态,除非客户端将发送带有 cookie 的新请求。

回答by Computer Tuts

Try setting cookie.Path = "/";

尝试设置 cookie.Path = "/";

Before you add the cookie.

在添加 cookie 之前。

回答by viniga

To set cookies value:

设置 cookie 值:

HttpCookie Userinfo= new HttpCookie("Userinfo");
Userinfo["Username"] = application.username.ToString();
Response.Cookies.Add(Userinfo);

To get cookies value:

获取 cookie 值:

HttpCookie reqUserinfocookies = Request.Cookies["Userinfo"];
if (reqUserinfocookies != null)
{
string username = reqUserinfocookies["username"];
}