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

15

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

document.cookie = "menuSize=Large";

我需要在 Razor 语法中访问这个 cookie,以便在用户更改页面时每次在 _Layout.cshtml 的顶部输出正确的样式:

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

你好,将值放入cookie中很重要吗?为什么不将其放入viewbag中呢?这样您就可以轻松访问它。据我所理解,在这里,您单击按钮,设置cookie并加载视图,因此您有一个postback。然后,正如我刚才提到的,为什么不将值放入viewbag中并在razor中捕获它。或者使用Request.Cookies,那么它将是:@Request.Cookies - alaa_sayegh
你有什么问题吗?你不知道如何访问 cookie 吗?Request.Cookie - Anis Alibegić
3个回答

17

您可以使用这种方式获取cookie值。还要确保您的cookie域路径是根路径。此外,您可以编写一些帮助方法以在C#中获取cookie值。

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

7
由于某些原因,Intellisense 无法识别 Request.Cookies。我最终使用 Context.Request 使其正常工作。这是因为我正在使用 ASP.NET MVC Core 吗? - Blake Rivell

1

我不得不去请求头手动获取在客户端创建/设置的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);
        }
    }
}

1

我遇到了同样的问题,然后做了这个:

@using Microsoft.AspNetCore.Http;

@{

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接