access cookie in _Layout.cshtml in ASP.NET Core

20,006

Solution 1

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).

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
    }
}

Solution 2

So I found the solution, if anyone needs it, too:

Add into ConfigureServices the service for IHttpContextAccessor

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

into your _Layout.cs inject IHttpContextAccessor:

@inject IHttpContextAccessor httpContextaccessor

access the cookies with

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

Solution 3

You don't need Dependency Injection or anything else. You access cookie on ASP.NET Core 2.0 MVC in view like that:

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

Solution 4

There is another way to handle your case: using view component.

Here is a simple example for your case:

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:

@await Component.InvokeAsync("LoggedInComponent")

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

Edit for directly access 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

Solution 5

CookieManager wrapper allows you to read/write/update/delete http cookie in asp.net core. it has fluent API's to ease of use.

Try my 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

just add the CookieManager in configure service in start up class

//add CookieManager
services.AddCookieManager();

In Layout page inject the Cookie Manager

@inject CookieManager.ICookie _httpCookie

_httpCookie.Get("Bearer")
Share:
20,006

Related videos on Youtube

Matthias Burger
Author by

Matthias Burger

Software-Development in C#.NET/.NET Core and Python. A few of my public projects: Extension-Library for .NET: IronSphere.Extensions. Json To C# - Visual-Studio-Plugin: JsonToCsharp

Updated on February 17, 2020

Comments

  • Matthias Burger
    Matthias Burger about 4 years

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

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

    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");
    

    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.

    Any suggestions or ideas?

    • adem caglin
      adem caglin over 7 years
      Just a suggest: Instead of accessing cookie in _Layout.cshtml, i would use view component to handle your case. You can create a view component and pass cookie value as model property.
    • Matthias Burger
      Matthias Burger over 7 years
      wow, that's nice. didn't work with view components for now. thanks. You want to add an answere with an example here? ;)
  • Matthias Burger
    Matthias Burger over 7 years
    yep, finally I came to the same result :) but here, have my "accept" - this works :)
  • Ralf Bönning
    Ralf Bönning over 7 years
    @MatthiasBurger - thanks - we were working simultaniously; happy coding.
  • Tyeth
    Tyeth about 6 years
    Thanks, I was lost looking for Request under controllerbase forgetting it was context. A simple Context.Request.Cookies.Any(x=>x.Key=="NewTempUser") was enough for me.
  • Matthias Burger
    Matthias Burger about 5 years
    Thats basically the same thing, that Ralf Bönning does. Only thing is, you are accessing a specific value by key, and Ralf iterates through all keys.
  • Robin Wilson
    Robin Wilson about 5 years
    Yes it is similar but in the _Layout.cshtml page this doesn't work for me and produces an error string value = HttpContext.Request.Cookies.Get("Bearer"); whereas this does work @HttpContextAccessor.HttpContext.Request.Cookies.TryGetValue‌​("SystemDatabase", out string SystemDatabase) and with the try bit I think it would fail gracefully rather than show an unhandled exception if not found.