在ASP.NET Core中的_Layout.cshtml中访问cookie [英] access cookie in _Layout.cshtml in ASP.NET Core

查看:594
本文介绍了在ASP.NET Core中的_Layout.cshtml中访问cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to store an authentication-key into my cookies when login succeeded:

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

因此在控制器类中可以使用.我可以轻松创建和阅读我的cookie. 但是,现在我要检查,如果存在的话,请在我的_Layout.cshtml中读取cookie的值,并显示已登录用户的名称-或登录链接. 但是如何读取部分_Layout.cshtml中的cookie?

So in the controller-class this works. I can easily create and read my cookies. 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. But how can I read my cookies in the partial _Layout.cshtml?

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

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

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.

有什么建议或想法吗?

推荐答案

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

In ASP.NET Core there is no concept of a static HttpContext any more. Dependency Injection rules in the new 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).

使用IHttpContextAccessor,您可以像本例中那样获得HttpContext和cookie信息.

Using the IHttpContextAccessor you can get the HttpContext and the cookie information like in this example.

 @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

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

这篇关于在ASP.NET Core中的_Layout.cshtml中访问cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆