在ASP.NET Core MVC Razor视图中访问cookie值

时间:2017-08-02 05:14:15

标签: asp.net asp.net-mvc razor cookies asp.net-core-mvc

当用户点击按钮时,我使用JavaScript设置了一个Cookie:

document.cookie = "menuSize=Large";

我需要使用razor语法访问此cookie,以便每次用户更改页面时都可以在_Layout.cshtml顶部输出正确的样式:

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

3 个答案:

答案 0 :(得分:4)

您可以使用此方法获取Cookie值。还要确保您的cookie域路径是root。您也可以编写一些帮助方法来获取C#中的cookie值。

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

答案 1 :(得分:0)

我不得不去标题并手动拉出我在客户端创建/设置的cookie:

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

答案 2 :(得分:0)

我遇到了同样的问题,并且做到了:

@using Microsoft.AspNetCore.Http;

@{

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

}