access cookie in _Layout.cshtml in ASP.NET Core
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"])
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
}
}