Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 _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?

like image 275
Matthias Burger Avatar asked Aug 14 '16 19:08

Matthias Burger


People also ask

How do I access cookies in asp net?

You may use Request. Cookies collection to read the cookies. Show activity on this post. HttpContext.

What is the purpose of _layout Cshtml?

_Layout.cshtml This is used for common layout in web pages; it is like master page. The layout typically includes common user interface elements such as the app header, navigation or menu elements, and footer. Common HTML structures such as scripts and stylesheets are also frequently used by many pages within an app.

What is Aspnet cookies cookie?

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.


2 Answers

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     } } 
like image 70
Ralf Bönning Avatar answered Oct 10 '22 05:10

Ralf Bönning


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"]) 
like image 27
Matthias Burger Avatar answered Oct 10 '22 06:10

Matthias Burger