Matthias Burger Matthias Burger - 1 year ago 59
ASP.NET (C#) Question

access cookie in _Layout.cshtml in ASP.NET Core

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
and show the name of the logged in user - or the link to login.
But how can I read my cookies in the partial

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

doesn't work. It tries to add either
to my usings or says HttpContext is static and needs a reference to access

Any suggestions or ideas?

Answer Source

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 (

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