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.
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");
}
}
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With