简体   繁体   English

如何在C#和ASP.NET MVC中读/写cookie

[英]How can read / write cookie in C# & ASP.NET MVC

I have problem with cookies, this is my read and write code in the class: 我有cookie的问题,这是我在课堂上的读写代码:

public static class language
{
   public static void set_default(string name)
   {
       HttpContext.Current.Response.Cookies.Remove("language");
       HttpCookie language = new HttpCookie("language");
       language["name"] = name;
       language.Expires = DateTime.Now.AddDays(1d);
       HttpContext.Current.Response.Cookies.Add(language);
   }

   public static string get_default()
   {
       string name = string.Empty;
       HttpCookie langauge = HttpContext.Current.Response.Cookies.Get("language");
       name = langauge["name"];
       return name;
   }
}

When I go to the next page and use @language.get_default() to get the default language, the response is null - why? 当我转到下一页并使用@language.get_default()来获取默认语言时,响应为null - 为什么?

When writing cookies, you add cookies to Response . 编写cookie时,您可以向Response添加cookie。 when Reading them you should use Request : 阅读时你应该使用Request

HttpCookie language = HttpContext.Current.Request.Cookies.Get("language");

So the set_default() is correct, but you should make change to get_default() 所以set_default()是正确的,但你应该改变get_default()

am not sure language.Expires = DateTime.Now.AddDays(1d); 我不确定language.Expires = DateTime.Now.AddDays(1d); is correct. 是正确的。 DateTime.Now.AddDays accepts an integer and 1d is not. DateTime.Now.AddDays接受整数,而1d则不接受。

CREATE COOKIE: 创建COOKIE:

HttpContext.Response.Cookies.Append("language", "ENGLISH", new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(5)
            });

GET COOKIE: 得到COOKIE:

 string language = HttpContext.Request.Cookies["language"];

DELETE COOKIE: 删除COOKIE:

HttpContext.Response.Cookies.Append("language", "", new CookieOptions()
            {
                Expires = DateTime.Now.AddDays(-1)
            });

or 要么

HttpContext.Response.Cookies.Delete("language");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM