Accessing a cookie value in an ASP.NET Core MVC Razor view

Viewed 19245

I set a cookie using JavaScript when the user clicks a button:

document.cookie = "menuSize=Large";

I need to access this cookie in razor syntax so I can output the correct styles at the top of _Layout.cshtml every time the user changes pages:

    @{
        if (cookie == "Large")
        {
            <style>
LARGE STYLES
            </style>
        }
        else
        {
            <style>
SMALL STYLES
            </style>
        }
    }
3 Answers

I had to go to the headers and manually pull out my cookie THAT IS CREATED/SET ON THE CLIENT:

//HACK ridiculous i have to do all this instead of just getting the cookie from the cookies collection
var cookieFromHeaderString = (context.HttpContext.Request.Headers["Cookie"]).FirstOrDefault();

if (cookieFromHeaderString != null)
{

    string[] strArray = cookieFromHeaderString.Split(new string[] { "; " }, StringSplitOptions.None);
    string whCookie = strArray.Where(m => m.StartsWith("vpWH=")).FirstOrDefault();

    if (whCookie != null)
    {
        int start = whCookie.IndexOf("=") + 1;
        string cookieValue = whCookie.Substring(start);

        string[] whArray = cookieValue.Split(' ');

        int viewportWidth = 0;
        int viewportHeight = 0;

        if (whArray.Length == 2)
        {
            int.TryParse(whArray[0], out viewportWidth);
            int.TryParse(whArray[1], out viewportHeight);
        }
    }
}

I was having the same problem and did it:

@using Microsoft.AspNetCore.Http;

@{

    if (HttpContext.Request.Cookies["menuSize"].Value == "Large")
    {
        <style>
            LARGE STYLES
        </style>
    }

}
Related