【问题标题】:access cookie in _Layout.cshtml in ASP.NET Core在 ASP.NET Core 中访问 _Layout.cshtml 中的 cookie
【发布时间】:2016-12-21 02:29:26
【问题描述】:

登录成功后,我正在尝试将身份验证密钥存储到我的 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

有什么建议或想法吗?

【问题讨论】:

  • 只是一个建议:我会使用视图组件来处理您的情况,而不是访问_Layout.cshtml 中的cookie。您可以创建视图组件并将 cookie 值作为模型属性传递。
  • 哇,太好了。目前不适用于视图组件。谢谢。您想在这里添加一个带有示例的答案吗? ;)

标签: c# asp.net authentication cookies asp.net-core


【解决方案1】:

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

IHttpContextAccessor的服务添加到ConfigureServices

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

到你的_Layout.cs注入IHttpContextAccessor

@inject IHttpContextAccessor httpContextaccessor

通过

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 是的,最后我得到了相同的结果 :) 但在这里,让我的“接受” - 这行得通:)
    • @MatthiasBurger - 谢谢 - 我们同时工作;快乐编码。
    【解决方案3】:

    还有另一种处理你的情况的方法:使用视图组件。

    这是一个简单的例子:

    LoggedInComponent.cs:

    public class LoggedInComponent: ViewComponent
    {
        public async Task<IViewComponentResult> 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")
    

    How to access session from a view in ASP .NET Core MVC 1.0

    【讨论】:

      【解决方案4】:

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

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

      它有两个接口ICookie和ICookieManager,可以帮助你在asp.net core中玩http cookie

      只需在启动类的配置服务中添加 CookieManager

      //add CookieManager
      services.AddCookieManager();
      

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

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

      【讨论】:

        【解决方案5】:

        您不需要依赖注入或其他任何东西。您可以像这样访问 ASP.NET Core 2.0 MVC 上的 cookie:

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

        【讨论】:

        • 谢谢,我在控制器库下寻找请求时迷路了,忘记了它是上下文。一个简单的 Context.Request.Cookies.Any(x=>x.Key=="NewTempUser") 对我来说就足够了。
        【解决方案6】:

        我已经为此苦苦挣扎了大约 2 个小时,因为在 .NET Core 2.2 中这些方法都不适用于我在 _Layout.cshtml 中读取 cookie 值,从而导致空白值或错误。 我有一个 cookie 集,用于存储用户连接到的数据库的名称,我想在 Web 应用程序的页脚(即培训或实时)中显示它。

        起作用的是将以下内容添加到 _Layout.cshtml 的顶部:

        @using Microsoft.AspNetCore.Http
        @inject IHttpContextAccessor HttpContextAccessor
        

        然后我在我希望 cookie 的值出现的位置添加了这个:

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

        现在打印“Live System”或“Training System”。 无需更改 Startup.cs。

        【讨论】:

        • 这与 Ralf Bönning 所做的基本相同。唯一的问题是,您正在通过键访问特定值,而 Ralf 会遍历所有键。
        • 是的,它是相似的,但是在 _Layout.cshtml 页面中这对我不起作用并产生错误string value = HttpContext.Request.Cookies.Get("Bearer"); 而这确实有效@HttpContextAccessor.HttpContext.Request.Cookies.TryGetValue("SystemDatabase", out string SystemDatabase) 并且尝试位我认为它会失败优雅地而不是在未找到时显示未处理的异常。
        猜你喜欢
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-17
        • 1970-01-01
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        相关资源
        最近更新 更多