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

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

HttpContext.Response.Cookies.Append("Bearer", accessToken, cookieMonsterOptions); 

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

 string value = HttpContext.Request.Cookies.Get("Bearer"); 

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

有什么建议或想法吗?

在ASP.NET Core中,不再有静态HttpContext的概念。 新Microsoft Web Framework中的dependency injection规则。 关于视图,有@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 } } 

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

ConfigureServices添加到ConfigureServicesIHttpContextAccessor服务

 public void ConfigureServices(IServiceCollection services) { services.AddSingleton(); } 

进入你的_Layout.cs注入IHttpContextAccessor

 @inject IHttpContextAccessor httpContextaccessor 

访问cookie

 @Html.Raw(httpContextaccessor.HttpContext.Request.Cookies["Bearer"]) 

还有另一种处理案例的方法:使用视图组件。

以下是您案例的简单示例:

LoggedInComponent.cs

 public class LoggedInComponent: ViewComponent { public async Task InvokeAsync() { return View(HttpContext.Request.Cookies.Get("Bearer")); } } 

组件视图:

 @model string @Html.Raw(Model) 

_Layout.cshtml

 @await Component.InvokeAsync("LoggedInComponent") 

另请参阅https://docs.asp.net/en/latest/mvc/views/view-components.html

编辑以直接访问cookie

 @using Microsoft.AspNetCore.Http; @Context.Request.Cookies.Get("Bearer") 

请参阅如何从ASP .NET Core MVC 1.0中的视图访问会话

您不需要dependency injection或其他任何东西。 您可以在视图中访问ASP.NET Core 2.0 MVC上的cookie:

 @{ Context.Request.Cookies.TryGetValue("Bearer", out string value); } 

CookieManager包装器允许您在asp.net核心中读取/写入/更新/删除http cookie。 它具有流畅的API,易于使用。

试试我的nuget packge: https : //github.com/nemi-chand/CookieManager

它有两个界面ICookie和ICookieManager,可以帮助你在asp.net核心中使用http cookie

只需在启动类的configure服务中添加CookieManager即可

 //add CookieManager services.AddCookieManager(); 

在布局页面中注入Cookie管理器

 @inject CookieManager.ICookie _httpCookie _httpCookie.Get("Bearer")