What is the easiest way to create and read cookies on Blazor server side.
It seems all the solutions out there is for Blazor Web-assembly, and whenever I use those the Response.Cookies.Append("") and Request.Cookies[] options do not work.
5 Answers
Inside the wwwroot/index.html
(Blazor WebAssembly) or Pages/_Host.cshtml
(Blazor Server), write the following javascript code:
<script>
window.WriteCookie = {
WriteCookie: function (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
}
window.ReadCookie = {
ReadCookie: function (cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}
</script>
Then, write the following sample code into the Razor component (.razor):
@inject IJSRuntime JsRuntime;
<button class="btn" @onclick="WriteCookies">
Write Cookie
</button>
<button class="btn" @onclick="ReadCookies">
Read Cookie
</button>
<p>The cookie is @myCookieValue</p>
@code {
public string myCookieValue { get; set; } = "";
protected async Task WriteCookies()
{
await JsRuntime.InvokeAsync<object>("WriteCookie.WriteCookie", "cookieName", "cookieValue", DateTime.Now.AddMinutes(1));
}
protected async Task ReadCookies()
{
myCookieValue= await JsRuntime.InvokeAsync<string>("ReadCookie.ReadCookie", "cookieName");
}
}
-
When I tried the code document.cookie always returned empty string inside a component.– panpawelMay 6, 2021 at 14:57
I found a great solution to the Blazor Server Side Cookie issue using local storage.
Firstly, grab the NuGet Blazored LocalStorage using the following command:
Install-Package Blazored.LocalStorage
I had to update my System.Text.Json, do this from https://www.nuget.org/packages/System.Text.Json/
Add the following to Startup.cs in:
public void ConfigureServices(IServiceCollection services)
{
services.AddBlazoredLocalStorage(); // local storage
services.AddBlazoredLocalStorage(config =>
config.JsonSerializerOptions.WriteIndented = true); // local storage
}
Or in latest .NET versions
using Blazored.LocalSorage;
var builder = WebApplication.CreateBuilder(args);
// add after builder initialization:
builder.Services.AddBlazoredLocalStorage(); // local storage
builder.Services.AddBlazoredLocalStorage(config => config.JsonSerializerOptions.WriteIndented = true); // local storage
On your Razor page (I used Index.razor to test):
@page "/"
@inject Blazored.LocalStorage.ILocalStorageService localStorage
<button @onclick="HandleSubmit">Create Cookie</button> @* Create your cookie *@
@code{
public async Task HandleSubmit()
{
await localStorage.SetItemAsync("cookieName", "Jason Bourne");
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var cookieContent = await localStorage.GetItemAsync<string>("cookieName");
if (cookieContent == null)
{
Console.WriteLine("Cookie is blank");
}
else
{
Console.WriteLine("We have a cookie with contents: " + cookieContent);
}
}
}
-
3LocalStorage is not the same as a cookie though. Technically the other answer is the correct answer. Mar 17, 2021 at 4:01
If you want to access Cookies from Blazor Component you need inject IHttpContextAccessor like below
[Inject]
IHttpContextAccessor HttpContextAccessor { get; set; }
and then you can access Cookies from Request object using the injected HttpContextAccessor
var token = httpContextAccessor.HttpContext.Request.Cookies["access_token"];
To set access token, use:
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(1);
httpContextAccessor.HttpContext.Response.Cookies.Append("access_token", response.access_token, options);
if you want to access Cookies from Service then you need to add IHttpContextAccessor using dependency injection in constructor of your service as below:
public AccessoryService(HttpClient httpClient,
IHttpContextAccessor HttpContextAccessor)
{
this.httpClient = httpClient;
httpContextAccessor = HttpContextAccessor;
}
pls add services.AddHttpContextAccessor(); on startup for dependency injection.
finally you can call api using the token that retrieve from Request object:
public async Task<IEnumerable<AccessoryDto>> GetAccessories()
{
var token = httpContextAccessor.HttpContext.Request.Cookies["access_token"];
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",token);
var accessories = await httpClient.GetFromJsonAsync<AccessoryDto[]>("api/accessory");
return accessories;
}
-
3Just a note, to use IHttpContextAccessor you need to inject
services.AddHttpContextAccessor();
on startup. Oct 23, 2021 at 4:56 -
-
2How is this code works? Since Blazor server side request are WebSocket based with SignalR. Since it is not HTTP based then
HttpContext
will be NULL as mentioned here github.com/dotnet/aspnetcore/issues/18183– MajorJan 31 at 19:15
I tried the approach based on Blazored.LocalStorage and also the experimental package presented here
And, I must say they are very similar, but they have one inconvenient: the LocalStorage variables can be read only from OnAfterRenderAsync or OnInitializedAsync (InvalidOperationException: JavaScript interop calls cannot be issued at this time. etc...).
In my case, I need to access the LocalStorage from OnParametersSetAsync, so I used a simple controller like this:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
namespace MyNamespace.Controllers
{
[Route("[controller]/[action]")]
public class CookieController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CookieController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
[HttpGet]
public IActionResult Write(string key, string value, string redirectUri)
{
CookieOptions options = new CookieOptions
{
Expires = DateTime.Now.AddDays(30),
// F: the values of these settings depends on your needs https://web.dev/samesite-cookies-explained/
SameSite = SameSiteMode.Strict,
Secure = true
};
_httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);
return LocalRedirect(redirectUri);
}
}
}
in Startup.cs I add services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
and, inside the component:
@inject IHttpContextAccessor HttpContextAccessor
@code
{
private string cookieContent;
protected override async Task OnParametersSetAsync()
{
...
var context = HttpContextAccessor.HttpContext;
// F: check the existance HttpContext because of https://stackoverflow.com/questions/59538132/httpcontext-is-null-when-running-web-app-in-iis and https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1#iisiis-express-support
if (context != null)
{
var cookies = context.Request.Cookies;
var fst = cookies["myFstCookie"];
var snd = cookies["mySndCookie"];
}
}
}
No offense to the others, but these answers are probably more complicated than you need them.
You can use JavaScript Interop to do whatever you want client side. That way, you have direct control over everything, instead of relying on libraries or plugins.