加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

在asp.net中使用cookie mvc c#

发布时间:2020-12-16 00:42:21 所属栏目:asp.Net 来源:网络整理
导读:我想使用cookie在我的网站上注册几页的参数。我尝试了以下代码,但不像我想要的那样: public ActionResult Index(int? dep,int? cat) { ...... string theDept = Request.QueryString["dep"]; HttpCookie cookie = new HttpCookie("search"); cookie.Values
我想使用cookie在我的网站上注册几页的参数。我尝试了以下代码,但不像我想要的那样:
public ActionResult Index(int? dep,int? cat)
 {
   ......
   string theDept = Request.QueryString["dep"];
   HttpCookie cookie = new HttpCookie("search");
   cookie.Values["dep_name"] = theDept;
   cookie.Expires = DateTime.Now.AddDays(1);
   Response.Cookies.Add(cookie);
   return View();
 }

我在site.master中看过:

<% 

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

if ((cookie != null) && (cookie.Value != ""))
{
    Response.Write(cookie.Values["dep_name"].ToString() + "---" +   
    cookie.Values["cat_name"].ToString() + "---" + cookie.Values["brand"].ToString());
}
%>

问题:当我点击另一个页面Request.QueryString [“dep”]为null时,我显示的cookie为null。

当我们还没有清除cookie时,如何将其存储在cookie中?

解决方法

我不知道我是否明白如果这是一个关于如何正确发送cookie到客户端或一些bug与您的querystring参数的问题。所以我会发布正确的方式发送cookie,如果我被误解,随时纠正我。

不管怎样,我相信:

HttpCookie cookie = new HttpCookie("search");

将重置搜索Cookie

得到一个cookie:

HttpCookie cookie = HttpContext.Request.Cookies.Get("some_cookie_name");

检查cookie的存在:

HttpContext.Request.Cookies["some_cookie_name"] != null

保存cookie:

HttpCookie cookie = new HttpCookie("some_cookie_name");
HttpContext.Response.Cookies.Remove("some_cookie_name");
HttpContext.Response.SetCookie(cookie );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读