31

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?

2
  • 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. Commented Aug 15, 2016 at 6:45
  • wow, that's nice. didn't work with view components for now. thanks. You want to add an answere with an example here? ;) Commented Aug 15, 2016 at 8:26

6 Answers 6

51

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

yep, finally I came to the same result :) but here, have my "accept" - this works :)
@MatthiasBurger - thanks - we were working simultaniously; happy coding.
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"])

Comments

15

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

2 Comments

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.
This worked for me @{ var MyNewTest = Context.Request.Cookies["SelectedSecurityOptions"]; }
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

Comments

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

Comments

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.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.