1

I want to ask that is there any way to read a cookie created by JavaScript code in the Controller?

My application is in ASP.NET Core.

In my View I am creating the cookie by JS like this:

<script type="text/javascript">
  document.cookie = "username=John Doe";
</script>

Now in my action method of the controller I try to read the cookie but it did not find any cookie there:

public IActionResult Index()
{
    var boh = Request.Cookies["username"];
    return View();
}

The value of boh comes out to be null saying no cookie.

I dug a bit deeper and inspected the "Network" area and found that cookie is not added to Response. See the below image:

enter image description here

If I can add the cookie to the response then I think it will be accessible in the controller, but how??

Is there any solution???

Thanks & Regards

yogihosting
  • 5,494
  • 8
  • 47
  • 80

2 Answers2

3

I found out that you need to encode the cookie value as pointed by out some expert. So I corrected it by doing the encoding:

$(function () {
  var cookieValue = encodeURIComponent("John Doe");
  document.cookie = "username=" + cookieValue;
});
yogihosting
  • 5,494
  • 8
  • 47
  • 80
1

After checking the cookies in HttpContext.Request.Headers, the cookie you set by document.cookie = "username=John Doe"; is stored in HttpContext.Request.Headers["Cookie"].

Try code below to retrive the cookies.

StringValues values;
HttpContext.Request.Headers.TryGetValue("Cookie", out values);
var cookies = values.ToString().Split(';').ToList();
var result = cookies.Select(c => new { Key = c.Split('=')[0].Trim(), Value = c.Split('=')[1].Trim() }).ToList();
var username = result.Where(r => r.Key == "username").FirstOrDefault();
Edward
  • 28,296
  • 11
  • 76
  • 121