11

I have a simple ASP.NET Core 2.1 application which is supposed to set and then read a cookie.

Whenever I try to read the cookie it returns null. Looking further in the browser's inspect tool I am unable to find it.

I came up with this small implementation to see if I can sort out whats going on, but it is not working..

 public async Task<IActionResult> Contact(Contato contato)
 {
    await email.SendAsync(contato);

    var option = new CookieOptions();
    option.Expires = DateTime.Now.AddMinutes(10);
    Response.Cookies.Append("EmailEnviado", "true", option);
    var boh = Request.Cookies["EmailEnviado"];

    return RedirectToAction("Contact");
 }

The variable boh, when inspected through the debugger is null, even though it was written in the previous line.

Simply Ged
  • 8,250
  • 11
  • 32
  • 40
Sergio Di Fiore
  • 446
  • 1
  • 8
  • 22
  • 2
    You're adding the cookie to the **Response.Cookies** collection but then trying to read from **Request.Cookies**. They are two separate collections. – Brad Sep 05 '18 at 23:41
  • 2
    @Martijn Pieters, this is not a duplicate of the linked issue, this is about cookies rather than session. – Tratcher May 06 '19 at 17:02
  • @Tratcher: the answer there had been copied to this question and marked accepted, so the OP of this question thought that that answer answered their problem. If you want to vote to reopen, then go ahead, this is not my field of expertise, I went with what the OP indicated. – Martijn Pieters May 07 '19 at 10:06
  • fwiw I would seriously doubt the answers to that other question would have really solved this problem and the remaining answer on this question seems to have hit the nail on the head. By adding a cookie to Response.Cookies it wouldn't have automatically appeared in Request.Cookies without finishing the http request and initiating another http request between the two – rdans Sep 18 '20 at 09:56

1 Answers1

23

You won't be able to read the cookie right after you set it the first time. Once the cookie is created by the response, you will be able to read it. Consider this:

public async Task<IActionResult> OnPostCreateAsync()
{

    var option = new CookieOptions();
    option.Expires = DateTime.Now.AddMinutes(10);
    Response.Cookies.Append("Emailoption", "true", option);
    return RedirectToPage();
}

And then you can read the cookie in the Get method:

public void OnGet()
{
    var boh = Request.Cookies["Emailoption"];
}