简体   繁体   English

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

[英]access cookie in _Layout.cshtml in ASP.NET Core

I'm trying to store an authentication-key into my cookies when login succeeded: 我正在尝试在登录成功时将身份验证密钥存储到我的cookie中:

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

So in the controller-class this works. 所以在控制器类中这是有效的。 I can easily create and read my cookies. 我可以轻松创建和阅读我的cookie。 But now I want to check and, if it exists, read the value of a cookie in my _Layout.cshtml and show the name of the logged in user - or the link to login. 但现在我想检查,如果它存在,请在我的_Layout.cshtml读取cookie的值,并显示登录用户的名称 - 或登录的链接。 But how can I read my cookies in the partial _Layout.cshtml ? 但是如何在部分_Layout.cshtml读取我的cookie?

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

doesn't work. 不起作用。 It tries to add either System.Web to my usings or says HttpContext is static and needs a reference to access Request . 它试图将System.Web添加到我的使用中,或者说HttpContext是静态的并且需要访问Request的引用。

Any suggestions or ideas? 有什么建议或想法吗?

In ASP.NET Core there is no concept of a static HttpContext any more. 在ASP.NET Core中,不再有静态HttpContext的概念。 Dependency Injection rules in the new Microsoft Web Framework. 新Microsoft Web Framework中的依赖注入规则。 Regarding views there is the @inject directive for accessing registered services like IHttpContextAccessor service ( https://docs.asp.net/en/latest/mvc/views/dependency-injection.html ). 关于视图,有@inject指令用于访问IHttpContextAccessor服务( https://docs.asp.net/en/latest/mvc/views/dependency-injection.html )等注册服务。

Using the IHttpContextAccessor you can get the HttpContext and the cookie information like in this example. 使用IHttpContextAccessor您可以获得HttpContext和cookie信息,如本例所示。

 @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

 @{
    foreach (var cookie in HttpContextAccessor.HttpContext.Request.Cookies)
    {
        @cookie.Key  @cookie.Value
    }
}

So I found the solution, if anyone needs it, too: 所以我找到了解决方案,如果有人需要的话:

Add into ConfigureServices the service for IHttpContextAccessor ConfigureServices添加到ConfigureServicesIHttpContextAccessor服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

into your _Layout.cs inject IHttpContextAccessor : 进入你的_Layout.cs注入IHttpContextAccessor

@inject IHttpContextAccessor httpContextaccessor

access the cookies with 访问cookie

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

There is another way to handle your case: using view component. 还有另一种处理案例的方法:使用视图组件。

Here is a simple example for your case: 以下是您的案例的简单示例:

LoggedInComponent.cs : LoggedInComponent.cs

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

Component View: 组件视图:

@model string

@Html.Raw(Model)

_Layout.cshtml : _Layout.cshtml

@await Component.InvokeAsync("LoggedInComponent")

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

Edit for directly access cookie 编辑以直接访问cookie

@using Microsoft.AspNetCore.Http;

@Context.Request.Cookies.Get("Bearer")

See How to access session from a view in ASP .NET Core MVC 1.0 请参阅如何从ASP .NET Core MVC 1.0中的视图访问会话

You don't need Dependency Injection or anything else. 您不需要依赖注入或其他任何东西。 You access cookie on ASP.NET Core 2.0 MVC in view like that: 您可以在视图中访问ASP.NET Core 2.0 MVC上的cookie:

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

CookieManager wrapper allows you to read/write/update/delete http cookie in asp.net core. CookieManager包装器允许您在asp.net核心中读取/写入/更新/删除http cookie。 it has fluent API's to ease of use. 它具有流畅的API,易于使用。

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

It has two interface ICookie and ICookieManager which helps you to play with http cookie in asp.net core 它有两个界面ICookie和ICookieManager,可以帮助你在asp.net核心中使用http cookie

just add the CookieManager in configure service in start up class 只需在启动类的configure服务中添加CookieManager即可

//add CookieManager
services.AddCookieManager();

In Layout page inject the Cookie Manager 在布局页面中注入Cookie管理器

@inject CookieManager.ICookie _httpCookie

_httpCookie.Get("Bearer")

I've struggled with this for about 2 hours as none of these methods work for me in .NET Core 2.2 to read a cookie value in _Layout.cshtml resulting in either a blank value or an error. 因为在.NET Core 2.2中,这些方法都不适用于读取_Layout.cshtml中的cookie值导致空白值或错误,所以我已经在这方面努力了大约2个小时。 I have a cookie set that stores the name of the database the user is connected to and I want to show this in the footer of the web application (ie Training or Live). 我有一个cookie集,用于存储用户连接到的数据库的名称,我想在Web应用程序的页脚中显示它(即Training或Live)。

What did work was to add the following to the top of _Layout.cshtml: 做了什么工作是将以下内容添加到_Layout.cshtml的顶部:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor

Then I added this at the location where I wanted the value of the cookie to appear: 然后我在想要显示cookie值的位置添加了这个:

@if (@HttpContextAccessor.HttpContext.Request.Cookies.TryGetValue("SystemDatabase", out string SystemDatabase))
{
  @SystemDatabase @:System
}
else
{
  @:Live System
}

This now prints either "Live System" or "Training System". 现在打印“Live System”或“Training System”。 No changes to Startup.cs were required. 不需要对Startup.cs进行任何更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM