首页 > 解决方案 > 代码:在我的 html 文件中键入 c# 时,“Request.Cookies”无效

问题描述

我正在尝试获取 cookie 的值,并基于该值在页面顶部的导航栏中显示不同的链接。这是一个 ASP.NET Core MVC 3.1 应用程序。我收到一个错误,该词Request在这种情况下无效。有没有办法让该代码工作,或者是否需要不同的代码来获得该值?在我的启动文件中,我有代码:app.UseCookiePolicy();

<li class="nav-item">
    @{string signedUp = Request.Cookies["signedUp"]; } 
 
    @*if user's first time, show signup link, otherwise, then the if else below...*@

    @if (User.Identity.IsAuthenticated)
    {
        <a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="LogOut">Log Out</a>
    }
    else
    {
        <a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="LogIn">Log In</a>
    }
</li>

标签: c#htmlasp.net-mvccookies

解决方案


剃须刀页面有HttpContext并且Request是 的一部分Context

@{ string signedUp = Context.Request.Cookies["signedUp"]; }

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.httpcontext.request


推荐阅读