Milligran
Milligran

Reputation: 3171

How to access cookie across MVC views

In my MVC app I am trying to store a cookie in one page response and access it another:

So my /account/register controller has an action that calls a method to store a cookie

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

After a user registers I can see that the response(/account/register ) contains the cookie: Userid:"B6EAF085-247B-46EB-BB94-79779CA44A14

I now wish to access this cookie from another MVC page view - info/paymentsuccess

I tried assigning the value to Viewbag as

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

This returns null

how do I access this cookie from another page/MVC view and store it in Viewbag.userid?

Upvotes: 0

Views: 6518

Answers (3)

martinoss
martinoss

Reputation: 5458

After registering, do you create a new session? Maybe the cookie is set to the MinValue for Expires, which makes it a session cookie.

Try this:

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);
}

Upvotes: 0

RKT
RKT

Reputation: 114

You can access cookies value in your view using following:

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

Upvotes: 0

Andrew
Andrew

Reputation: 375

In your account register controller set the cookie:

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

You can retrieve the cookie like so in your post /account/register controller:

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

Upvotes: 1

Related Questions