在ASP.NET Core中的_Layout.cshtml中访问cookie

Mat*_*ger 18 c# asp.net authentication cookies asp.net-core

我正在尝试在登录成功时将身份验证密钥存储到我的cookie中:

HttpContext.Response.Cookies.Append("Bearer", accessToken, cookieMonsterOptions);
Run Code Online (Sandbox Code Playgroud)

所以在控制器类中这是有效的.我可以轻松创建和阅读我的cookie.但是现在我想检查一下,如果它存在,请读取我的cookie的值,_Layout.cshtml并显示登录用户的名称 - 或登录的链接.但是如何在部分中读取我的cookie _Layout.cshtml

string value = HttpContext.Request.Cookies.Get("Bearer");
Run Code Online (Sandbox Code Playgroud)

不起作用.它试图添加System.Web到我的使用或者说HttpContext是静态的并且需要访问的引用Request.

有什么建议或想法吗?

Ral*_*ing 26

在ASP.NET Core中,不再有静态HttpContext的概念.新Microsoft Web Framework中的依赖注入规则.关于视图,有关于@inject访问服务等注册服务的指令IHttpContextAccessor(https://docs.asp.net/en/latest/mvc/views/dependency-injection.html).

使用IHttpContextAccessor你可以获得HttpContext和本例中的cookie信息一样.

 @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

 @{
    foreach (var cookie in HttpContextAccessor.HttpContext.Request.Cookies)
    {
        @cookie.Key  @cookie.Value
    }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ger 12

所以我找到了解决方案,如果有人需要的话:

添加到ConfigureServices服务中IHttpContextAccessor

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
Run Code Online (Sandbox Code Playgroud)

进入你的_Layout.cs注入IHttpContextAccessor:

@inject IHttpContextAccessor httpContextaccessor
Run Code Online (Sandbox Code Playgroud)

访问cookie

@Html.Raw(httpContextaccessor.HttpContext.Request.Cookies["Bearer"])
Run Code Online (Sandbox Code Playgroud)


Ire*_*ren 9

您不需要依赖注入或其他任何东西。您可以在ASP.NET Core 2.0 MVC上访问 cookie,如下所示:

@{
Context.Request.Cookies.TryGetValue("Bearer", out string value);
}
Run Code Online (Sandbox Code Playgroud)