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?
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
}
}
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"])
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
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);
}
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")
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 (ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.