28

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?

Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
Matthias Burger
  • 5,549
  • 7
  • 49
  • 94
  • 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. – adem caglin Aug 15 '16 at 06:45
  • 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 Aug 15 '16 at 08:26

6 Answers6

48

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
    }
}
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
16

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"])
Matthias Burger
  • 5,549
  • 7
  • 49
  • 94
11

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);
}
Iren Saltalı
  • 516
  • 7
  • 16
  • 1
    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. – Tyeth Mar 30 '18 at 23:11
3

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

Community
  • 1
  • 1
adem caglin
  • 22,700
  • 10
  • 58
  • 78
2

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")
Undo
  • 25,519
  • 37
  • 106
  • 129
Nemi Chand
  • 138
  • 1
  • 10
1

I've struggled with this for about 2 hours as none of these methods work for me in .NET Core 2.2 to read a cookie value in _Layout.cshtml resulting in either a blank value or an error. I have a cookie set that stores the name of the database the user is connected to and I want to show this in the footer of the web application (i.e. Training or Live).

What did work was to add the following to the top of _Layout.cshtml:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor

Then I added this at the location where I wanted the value of the cookie to appear:

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

This now prints either "Live System" or "Training System". No changes to Startup.cs were required.

Robin Wilson
  • 308
  • 2
  • 11
  • 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. – Matthias Burger Apr 15 '19 at 10:07
  • 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. – Robin Wilson Apr 16 '19 at 12:19