在asp.net mvc的C#中使用的cookie [英] Using cookie in asp.net mvc c#

查看:1191
本文介绍了在asp.net mvc的C#中使用的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要注册使用的cookie在我的网站几页的参数。我想下面的code,但不是说我想要什么:

I want to register the parameter of a few pages in my web site using cookie. I tried the below code but not like what I want :

 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阅读:

I read it in 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] 为空,我显示Cookie是空来。

Problem: When I click to another page that Request.QueryString["dep"] is null, the cookie that I display is null to.

如何将其存储在cookie中不失,而我们尚不清楚的cookie?

How to store it in the cookie without losing while we not yet clear the cookie?

感谢这么多,欢迎你的答案。

Thank so much and welcome to your answers.

推荐答案

我不敢肯定我的理解,如果这是一个关于如何正确发送cookie到客户端或一些bug与你的查询字符串PARAMS问题。所以,我会邮寄cookie的正确方法,并随时纠正我,如果我误解了。

I m not sure I understand if this is a question about how to properly send cookies to the client or some bug with your querystring params. So I ll post the proper way of sending cookies and feel free to correct me if I misunderstood.

在任何虽然情况下,我相信这一点:

In any case though, I believe this:

HttpCookie cookie = new HttpCookie("search");

将重置搜索的cookie

will reset the search cookie

要得到一个cookie:

To get a cookie:

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

要检查一个cookie的存在:

To check for a cookie's existence:

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

要保存一个cookie:

To save a cookie:

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

这篇关于在asp.net mvc的C#中使用的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆