如何跨MVC视图访问cookie

时间:2014-02-16 22:56:05

标签: asp.net-mvc

在我的MVC应用程序中,我试图将cookie存储在一个页面响应中并访问另一个:

所以我的/account/register控制器有一个动作来调用存储cookie的方法

public void StoreCookie(Guid pid)
{
        var userCookie = new HttpCookie("Userid","B6EAF085-247B-46EB-BB94-79779CA44A14");
        Response.Cookies.Remove("Userid");
        Response.Cookies.Add(userCookie);
    }

用户注册后我可以看到响应(/ account / register)包含cookie:Userid:"B6EAF085-247B-46EB-BB94-79779CA44A14

我现在希望从另一个MVC页面视图中访问此cookie - info/paymentsuccess

我尝试将值分配给Viewbag

Viewbag.userid = @Response.Cookies["Userid"].value

这会返回null

如何从其他网页/ MVC视图访问此Cookie并将其存储在Viewbag.userid

3 个答案:

答案 0 :(得分:1)

在您的帐户注册控制器中设置Cookie:

HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

您可以在帖子/帐户/注册控制器中检索cookie:

if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
    HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
    // retrieve cookie data here
}

答案 1 :(得分:0)

您可以使用以下内容访问视图中的Cookie值:

  Viewbag.userid = @Request.Cookies["Userid"].value

答案 2 :(得分:0)

注册后,您是否创建了新会话?也许Cookie设置为MinValue Expireswhich makes it a session cookie

public void StoreCookie(Guid pid) { var userCookie = new HttpCookie("Userid","B6EAF085-247B-46EB-BB94-79779CA44A14"); userCookie.Expires = DateTime.Now.AddDays(1); //...or something that fit your needs Response.Cookies.Remove("Userid"); Response.Cookies.Add(userCookie); }

试试这个:

{{1}}