javascriptasp.net-corecookiesrazorgdprconsentform

Setting cookie in _layout.cshtml, not available when changing controllers


I'm setting up a gdpr cookie policy box. If the cookie is set, the box should not appear again.

I set the cookie as follows:

<button type="button" onclick="setCookie('cookiePolicy', '1')"> Accept </button>

Then I am showing the cookie box with this script:

$(window).on('load', function() {
  var cookieBox = document.cookie.indexOf('cookiePolicy');
  if (cookieBox == -1)
    $('#cookieBox').modal('show');
}

This works as intended within the login page to my asp.net webapp, however after calling a view from another controller than default, the cookie box will appear again. The cookie is not visible within chrome's devtools, either.

The cookie's path in this case is "/", while if I accept the cookie box on the new controller, the path for that instance will be "/Test" in the Test-Controller.

Is there a way to either: write the cookie to be accessible domain-wide, or read cookies domain-wide?

This is intended to work in asp.net core within the razor view .cshtml

Thanks in advance.

EDIT: The accepted answer has the desired effect, however to be noted is that this seems to also be default behavior. The actual issue was, that the cookie's path was automatically assigned, as it was not being set in the first place:

document.cookie = cName + "=" + cValue + ";"

adding the path explicitly stopped any wonky behavior and makes the cookie visible domain-wide, even if no "/" is present.

document.cookie = cName + "=" + cValue + ";" + ";path=/";

works for:

when set from anywhere within the domain localhost:port


Solution

  • you can read cookies domain-wide by adding the domain attribute when checking for the cookie

    $(window).on('load', function() {
      var cookieBox = document.cookie.indexOf('cookiePolicy');
      if (cookieBox == -1)
      $('#cookieBox').modal('show');
    }).attr('cookiePolicy', '1', {expires: 365, path: '/', domain: 'azerty.com'});
    

    Don't forget to replace "azerty.com" with your actual domain