In the Blazor Web assembly application, HttpClient doesn't include cookies with requests. If you wish to read/write cookies, you will have to use JS Interop.
1. Add javascript in index.html which contains code to read and write the cookie.
<script>
window.methods = {
CreateCookie: 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=/";
},
GetCookie: function (cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let 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>
2. To use javascript functions, inject IJSRuntime into the Razor page.
@inject IJSRuntime JSRuntime
@code {
private async void CreateCookie(string name, string value, int days)
{
var test = await JSRuntime.InvokeAsync<string>("methods.CreateCookie", name, value, days);
}
private async string GetCookie(string name)
{
return await JSRuntime.InvokeAsync<string>("methods.GetCookie", name);
}
}