Showing posts with label Blazor WASM. Show all posts
Showing posts with label Blazor WASM. Show all posts

Saturday, 4 January 2025

Slider component for Blazor

I have added a Blazor component for Blazor, which uses INPUT of type range and additional CSS styling for more flexible setup of look and feel. The Blazor component is available on Github in my repo here:

https://github.com/toreaurstadboss/BlazorSlider

Blazor lib component

This repository contains Blazor lib Slider component that shows an input of type 'range'.

The slider got default horizontal layout, where the minimum value for the slider is shown to the most left of the scale, which goes along the x-axis for the slider got towards higher values and the maximum value is the value to the most right. The slider x-axis goes along the 'slider track'.

The value of the slider is indicated by the 'slider thumb'. Below the slider are shown 'tick marks', which are controlled by the Minimum and Maximum values and StepSize. Note that the supported data types are the data types that are IConvertible and struct, and the code expects types that can be converted to double. You can use integers for example, but also decimals or floats and so on. In addition, enums can be used, but it works only if your enum got consecutive values, for example 0,1,2,3,4 . The best results are if these consecutive values got the same StepSize. To start using the Blazor slider, add this using in your .razor file where you want to use the component.
 
@using BlazorSliderLib

Please note that the slider has been tested using Bootstrap, more specifically this version:

"bootstrap@5.3.3"
Here is sample markup you can add to test out the Blazor slider (3 sliders are rendered using a custom model and the updated values are shown in labels below :

    <div class="container"> 

        <div class="row">
            <div class="form-control col-md-4">
                <p><b>EQ5D-5L question 1.</b> <br />Mobility. Ability to walk.</p>
                <BlazorSliderLib.Slider T="Eq5dWalk" UseAlternateStyle="AlternateStyle.AlternateStyleInverseColorScale" Title="Ability to walk" ValueChanged="@((e) => UpdateEq5dQ1(e))"
                MinimumDescription="No Problems = The best ability to walk you can imagine" MaximumDescription="Incapable = The worst ability to walk you can imagine" />
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p><b>EQ5D-5L question 6.</b> <br />We would like to how good or bad your health is TODAY.</p>
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <BlazorSliderLib.Slider T="int" UseAlternateStyle="AlternateStyle.AlternateStyle" Minimum="0" Maximum="100" @bind-Value="@(Model.Data.Eq5dq6)" Stepsize="5" Title="Your health today"
                MinimumDescription="0 = The worst health you can imagine" MaximumDescription="100 = The best health you can imagine" />
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p><b>EQ5D-5L question 6.</b> <br />We would like to how good or bad your health is TODAY. V2 field.</p>
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <BlazorSliderLib.Slider T="int" Minimum="0" Maximum="100" ValueChanged="@((e) => UpdateEq5dq6V2(e))" Stepsize="5" Title="Your health today (v2 field)"
                MinimumDescription="0 = The worst health you can imagine" MaximumDescription="100 = The best health you can imagine" />
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p>Value of Model.Data.Eq5dq1</p>
                @Model.Data.Eq5dq1
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4"> <p>Value of Model.Data.Eq5d6</p>
                @Model.Data.Eq5dq6 
            </div> 
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p>Value of Model.Data.Eq5d6V2</p>
                @Model.Data.Eq5dq6V2
            </div>
        </div>

    </div>

The different setup of sliders

The slider is set up either with an alternate style or using the default styling for sliders, that is, the slider uses an input type of 'range' and the default documented styling on Mozilla Developer Network (MDN) to render a Blazor slider. In addition, it is possible to set up the alternate style to use a inverted color range where higher values will get a reddish color and lower values will get a greenish color. The standard alternate style will show greenish colors for higher values. The following screenshot shows the possible styling that is possible. Note that the default styling is shown in the slider at the bottom, which will render a bit different in different browsers. In Chrome for example, the slider will render with a bluish color. In Edge Chromium, a grayish color is used for the 'slider tick' and 'slider thumb'. Screenshots showing the sliders: The following parameters can be used:
Title
Required. The title is shown below the slider component and centered horizontally along the center of the x-axis which the slider is oriented.
Value
The value of the slider. It can be data bound using either the @bind-Value directive attribute that supports two-way data binding. You can instead use the @ValueChanged event callback, if desired.
Minimum
The minimum value along the slider. It is default set to 0 for numbers. For enums, the lowest value is chosen of the enum (minimum enum alternative, converted to double internally).
Maximum
The maximum value along the slider. It is default set to 100 for numbers. For enums, the higheset value is chosen of the enum (maximum enum alternative, converted to double internally).
Stepsize
The step size for the slider. It is default set to 5 for numbers. For enums, it is set to 1. (note that internally the slider must use double values to work with the _tickmarks_, which expects double values).
ShowTickmarks
Shows tick marks for slider. It is default set to 'true'. Tick marks are generated from the values of Minimum, Maximum and StepSize.
MinimumDescription
Shows additionally description for the minimum value, shown as a small label below the slider. It will only be shown in the value is not empty.
UseAlternateStyle
If the UseAlternateStyle is set to either AlternateStyle and AlternateStyleInverseColorScale, alternate styling is used.

CSS rules to enable the slider

Actually, it is necessary to define a set of CSS rules to make the slider work. The slider's css rules are defined in two different files.

Default CSS rules

`Slider.css` The CSS rules below are taken from MDN Mozilla Developer Network page for the input type 'range' control. Input type 'range' control MDN article:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range

Additional settings are set up. The width is set to 100% so the slider can get as much horizontal space as possible and 'stretch'. There are also basic styles set up for both the tick label and datalist.The datalist is the tickmarks for the slider. The tick marks are automatically generated for the slider.


.sliderv2
{
    width:100%;
}

.sliderv2Label {
    font-weight: 400;
    text-align: center;
    left: 50%;
    font-size:0.7em;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, margin-bottom: 2px;
}

datalist {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    writing-mode: vertical-lr;
    width: 100%;
}

.tick-label {

    justify-content: space-between;
    font-size:0.6em;

    top: 20px; /* Adjust this value as needed */
}

input[type="range"] {
    width: 100%;
    margin: 0;
}


Alternate CSS rules

`SliderAlternate.css` The alternate CSS rules are setting up additional styling, where color encoding is used for the 'slider track' where higher values along the 'slider track' get a more 'greenish color', while lower values gets 'reddish values'. It is possible to set up the inverse color encoding here, with higher values getting 'reddish color'. Lower values gets more 'greenish colors' in this setup.


.alternate-style input[type="range"] {
    -webkit-appearance: none; /* Remove default styling */
    width: 100%;
    height: 8px;
    background: #ddd;
    outline: none;
    opacity: 0.7;
    transition: opacity .2s;
}

    .alternate-style input[type="range"]:hover {
        opacity: 1;
    }

    .alternate-style input[type="range"]::-webkit-slider-runnable-track {
        width: 100%;
        height: 8px;
        background: linear-gradient(to left, #A5D6A7, #FFF9C4, #FFCDD2); /* More desaturated gradient color */
        border: none;
        border-radius: 3px;
    }

        .alternate-style-inverse-colorscale input[type="range"]::-webkit-slider-runnable-track {
            background: linear-gradient(to right, #A5D6A7, #FFF9C4, #FFCDD2) !important; /* More desaturated gradient color, inverted color range */
        }


.alternate-style input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; /* Remove default styling */
    appearance: none;
    width: 25px;
    height: 25px;
    background: #2E7D32; /* Even darker green thumb color */
    cursor: pointer;
    border-radius: 50%;
    margin-top: -15px !important; /* Move the thumb up */
}

    .alternate-style input[type="range"]::-moz-range-track {
        width: 100%;
        height: 8px;
        background: linear-gradient(to left, #A5D6A7, #FFF9C4, #FFCDD2); /* More desaturated gradient color */
        border: none;
        border-radius: 3px;
    }

        .alternate-style-inverse-colorscale input[type="range"]::-moz-range-track {
            background: linear-gradient(to right, #A5D6A7, #FFF9C4, #FFCDD2 !important; /* More desaturated gradient color, inverted color range */
        }

    .alternate-style input[type="range"]::-moz-range-thumb {
        width: 25px;
        height: 25px;
        background: #2E7D32; /* Even darker green thumb color */
        cursor: pointer;
        border-radius: 50%;
        transform: translateY(-15px); /* Move the thumb up */
    }


The implementation for the Blazor slider looks like this, in the codebehind file for the Slider:


using Microsoft.AspNetCore.Components;

namespace BlazorSliderLib
{

    /// <summary>
    /// Slider to be used in Blazor. Uses input type='range' with HTML5 element datalist and custom css to show a slider.
    /// To add tick marks, set the <see cref="ShowTickmarks"/> to true (this is default)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public partial class Slider<T> : ComponentBase
        where T : struct, IComparable
    {

        /// <summary>
        /// Initial value to set to the slider, data bound so it can also be read out
        /// </summary>
        [Parameter]
        public T Value { get; set; }

        public double ValueAsDouble { get; set; }

        public double GetValueAsDouble()
        {
            if (typeof(T).IsEnum)
            {
                if (_isInitialized)
                {
                    var e = _enumValues.FirstOrDefault(v => Convert.ToDouble(v).Equals(Convert.ToDouble(Value)));
                    return Convert.ToDouble(Convert.ChangeType(Value, typeof(int)));
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return Convert.ToDouble(Value);
            }
        }        

        [Parameter, EditorRequired]
        public required string Title { get; set; }

        [Parameter]
        public string? MinimumDescription { get; set; }

        [Parameter]
        public string? MaximumDescription { get; set; }

        [Parameter]
        public double Minimum { get; set; } = typeof(T).IsEnum ? Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Min() : 0.0;

        [Parameter]
        public double Maximum { get; set; } = typeof(T).IsEnum ? Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Max() : 100.0;

        [Parameter]
        public double? Stepsize { get; set; } = typeof(T).IsEnum ? 1 : 5.0;

        [Parameter]
        public bool ShowTickmarks { get; set; } = true;

        [Parameter]
        public AlternateStyle UseAlternateStyle { get; set; } = AlternateStyle.None;

        [Parameter]
        public EventCallback<T> ValueChanged { get; set; }

        public List<double> Tickmarks { get; set; } = new List<double>();

        private List<T> _enumValues { get; set; } = new List<T>();

        private bool _isInitialized = false;

        private async Task OnValueChanged(ChangeEventArgs e)
        {
            if (e.Value == null)
            {
                return;
            }
            if (typeof(T).IsEnum && e.Value != null)
            {
                var enumValue = _enumValues.FirstOrDefault(v => Convert.ToDouble(v).Equals(Convert.ToDouble(e.Value))); 
                if (Enum.TryParse(typeof(T), enumValue.ToString(), out _)) {
                    Value = enumValue; //check that it was a non-null value set from the slider
                }
                else
                {
                    return; //if we cannot handle the enum value set, do not process further
                }
            }
            else
            {
                Value = (T)Convert.ChangeType(e.Value!, typeof(T));
            }

            ValueAsDouble = GetValueAsDouble();

            await ValueChanged.InvokeAsync(Value);
        }


        private string TickmarksId = "ticksmarks_" + Guid.NewGuid().ToString("N");

        protected override async Task OnParametersSetAsync()
        {
            if (_isInitialized)
            {
                return ; //initialize ONCE 
            }

            if (!typeof(T).IsEnum && Value.CompareTo(0) == 0)
            {
                Value = (T)Convert.ChangeType((Convert.ToDouble(Maximum) - Convert.ToDouble(Minimum)) / 2, typeof(T));
                ValueAsDouble = GetValueAsDouble();
            }

            if (Maximum.CompareTo(Minimum) < 1)
            {
                throw new ArgumentException("The value for parameter 'Maximum' is set to a smaller value than {Minimum}");
            }
            GenerateTickMarks();

            BuildEnumValuesListIfRequired();

            _isInitialized = true;

            await Task.CompletedTask;
        }

        private void BuildEnumValuesListIfRequired()
        {
            if (typeof(T).IsEnum)
            {
                foreach (var item in Enum.GetValues(typeof(T)))
                {
                    _enumValues.Add((T)item);
                }
            }
        }

        private void GenerateTickMarks()
        {
            Tickmarks.Clear();
            if (!ShowTickmarks)
            {
                return;
            }
            if (typeof(T).IsEnum)
            {
                int enumValuesCount = Enum.GetValues(typeof(T)).Length;
                double offsetEnum = 0;
                double minDoubleValue = Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Min();
                double maxDoubleValue = Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Max();
                double enumStepSizeCalculated = (maxDoubleValue - minDoubleValue) / enumValuesCount;

                foreach (var enumValue in Enum.GetValues(typeof(T)))
                {
                    Tickmarks.Add(offsetEnum);
                    offsetEnum += Math.Round(enumStepSizeCalculated, 0);
                }
                return;
            }

            for (double i = Convert.ToDouble(Minimum); i <= Convert.ToDouble(Maximum); i += Convert.ToDouble(Stepsize))
            {
                Tickmarks.Add(i);
            }

        }      

    }

    public enum AlternateStyle
    {
        /// <summary>
        /// No alternate style. Uses the ordinary styling for the slider (browser default of input type 'range')
        /// </summary>
        None,

        /// <summary>
        /// Applies alternate style, using in addition to the 'slider track' an additional visual hint with an additional 'slider track' right below that shows a reddish color for lowest parts of the scale to the slider and towards yellow and greenish hues for higher values
        /// The alternate style uses a larger 'slider thumb' and alternate style to the 'slider-track'. The alternate style gives a more interesting look, especially in Microsoft Edge Chromium.
        /// </summary>
        AlternateStyle,

        /// <summary>
        /// Similar in style to the alternate style, but uses the inverse scale for the colors along the slider
        /// </summary>
        AlternateStyleInverseColorScale
    }

}


The markup of the Slider looks like this:


@using Microsoft.AspNetCore.Components.Forms
@using BlazorSliderLib
@typeparam T where T : struct, IComparable

<div class="slider-container sliderv2 @((UseAlternateStyle == AlternateStyle.AlternateStyle || (UseAlternateStyle == AlternateStyle.AlternateStyleInverseColorScale))? "alternate-style" : "") @(UseAlternateStyle == AlternateStyle.AlternateStyleInverseColorScale ? "alternate-style-inverse-colorscale" : "")">
<input type="range" @bind="@ValueAsDouble" min="@Minimum" max="@Maximum" step="@Stepsize" list="@TickmarksId" @oninput="OnValueChanged" />
<datalist id="@TickmarksId">
    @{
        var itemIndex = 0;
    }
    @foreach (var value in Tickmarks){
        if (typeof(T).IsEnum){
            var itemLabel = _enumValues.ElementAt(itemIndex);
            <option class="tick-label" value="@value" label="@itemLabel"></option>
        }
        else {
            <option class="tick-label" value="@value" label="@value"></option>
        }
        itemIndex++;    
    }
</datalist>

<div class="row">
@if (!string.IsNullOrWhiteSpace(MinimumDescription)){
    <div class="col-md-4">
        <label class="sliderv2Label text-muted">@MinimumDescription</label>
    </div>
}
@if (!string.IsNullOrWhiteSpace(Title)){
    <div class="col-md-4">
        <label class="sliderv2Label text-muted" style="text-align:center">@Title: @Value</label>
    </div>
}

@if (!string.IsNullOrWhiteSpace(MaximumDescription)){
    <div class="col-md-4" style="text-align:right">
        <label class="sliderv2Label tet-muted text-end">@MaximumDescription</label>
    </div>
}

</div>

<link rel="stylesheet" href="_content/BlazorSliderLib/Slider.css" />
<link rel="stylesheet" href="_content/BlazorSliderLib/SliderAlternate.css" />

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>


</div>


The slider control is provided "as is" and is free to change and use of no charge.

https://github.com/toreaurstadboss/BlazorSlider?tab=MIT-1-ov-file#readme

Tuesday, 4 July 2023

Writing cookies with Blazor WASM

This article presents some source code of how to write and read cookies from Blazor WebAssembly - WASM. For Blazor WASM, we are going to use Javascript to write these cookies. Blazor WASM has not an easy way to write these cookies programatically, as the use of HttpContext accessor is discouraged and not available, i.e. you cannot just add cookies without round trips to backend services.

But via Js, the client can write cookies. I looked into a helper lib to write such cookies and do so using different attribute values for the cookies.
The following Mozilla Developer Network (MDN) page is helpful in detailing cookies, which attribute values can be set on them. Cookies are used to give user experience since they track user's on a web site and give tailored user experience - and advertising - and also can track the users accross servers / web sites as third-party cookies. They are small string values that are either stored on clients inside cookie storage in the browser's folder on the user's hard drive or in memory or other place such as partitioned cookies.

MND page - document.cookies

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie First off, the source code is here:

Forked Repo with adaptions in cookie handling for Blazor WASM

https://github.com/toreaurstadboss/AltairCA.Blazor.WebAssembly.Cookie This is a forked repo from this repo:

Original repo with cookie handling for Blazor WASM

https://github.com/AltairCA/AltairCA.Blazor.WebAssembly.Cookie The most recent branch of mine is this one: https://github.com/toreaurstadboss/AltairCA.Blazor.WebAssembly.Cookie/blob/feature/more-cookie-keys/README.md
Let's first look at the interface for the util class that will write cookies :

Interface for cookie handling for Blazor.wasm, IAltairCABlazorCookieUtil.cs

 
 
using AltairCA.Blazor.WebAssembly.Cookie.Models;

namespace AltairCA.Blazor.WebAssembly.Cookie
{
    public interface IAltairCABlazorCookieUtil
    {
        /// <summary>
        /// Set a object in the cookie
        /// </summary>
        /// <param name="key">The key for the cookie (name)</param>
        /// <param name="value">Cookie value</param>
        /// <param name="span">TimeSpan that will be set to the 'expires' attribute value</param>
        /// <param name="path">Path in the request url which must exist for the cookie to be sent in requests </param>
        /// <param name="domain">The host to which the cookie will be sent</param>
        /// <param name="secure">Specifies that the cookie will be sent only over secure protocols</param>
        /// <param name="isSession">Flags the cookie as a session cookie (temporal) by setting the 'expires' attribute value to ''</param>
        /// <param name="partitioned">Requires that the browser has activated partitioned cookies</param>
        /// <param name="maxAgeInSeconds">Maximum age in seconds</param> 
        /// <returns></returns>
        Task SetValueAsync(string key, object value, TimeSpan? span = null, string? path = null,
            string? domain = null, bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, 
            bool? isSession = null, int? maxAgeInSeconds = null);

        /// <summary>
        /// Set a string in the cookie
        /// </summary>
        /// <param name="key">The key for the cookie (name)</param>
        /// <param name="value">Cookie value</param>
        /// <param name="span">TimeSpan that will be set to the 'expires' attribute value</param>
        /// <param name="path">Path in the request url which must exist for the cookie to be sent in requests </param>
        /// <param name="domain">The host to which the cookie will be sent</param>
        /// <param name="secure">Specifies that the cookie will be sent only over secure protocols</param>
        /// <param name="isSession">Flags the cookie as a session cookie (temporal) by setting the 'expires' attribute value to ''</param>
        /// <param name="partitioned">Requires that the browser has activated partitioned cookies</param>
        /// <param name="maxAgeInSeconds">Maximum age in seconds</param> 
        /// <returns></returns>
        Task SetValueAsync(string key, string value, TimeSpan? span = null, string? path=null, string? domain=null, 
            bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, bool? isSession = null,
            int? maxAgeInSeconds = null);
       
        Task<string> GetValueAsync(string key);
       
        Task<T> GetValueAsync<T>(string key) where T : class;
        
        Task RemoveAsync(string key, string? path = null);

    }
}
 
 
And here is the implementation.

Implementation for cookie handling for Blazor.wasm, AltairCABlazorCookieUtil.cs

 
 
using System.ComponentModel;
using AltairCA.Blazor.WebAssembly.Cookie.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.JSInterop;
using Newtonsoft.Json;

namespace AltairCA.Blazor.WebAssembly.Cookie
{

    internal class AltairCABlazorCookieUtil : IAltairCABlazorCookieUtil
    {
        readonly IJSRuntime JSRuntime;
        private readonly AltairCABlazorCookieConfigOptions _settings;
        public AltairCABlazorCookieUtil(IJSRuntime jsRuntime,IOptions<AltairCABlazorCookieConfigOptions> options)
        {
            JSRuntime = jsRuntime;
            _settings = options.Value;
        }

        public Task SetValueAsync(string key, object value, TimeSpan? span = null, string? path = null,
            string? domain = null, bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, bool? isSession = null,
            int? maxAgeInSeconds = null)
        {
            return SetValueAsync(key, JsonConvert.SerializeObject(value), span, path, domain, secure, sameSite, partitioned,
                isSession);
        }
        public async Task SetValueAsync(string key, string value, TimeSpan? span = null, string? path=null, string? domain=null, 
            bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, bool? isSession = null,
             int? maxAgeInSeconds = null)
        {
            if (string.IsNullOrWhiteSpace(path))
                path = _settings.Path;
            if (!span.HasValue)
                span = _settings.DefaultExpire;
            if (string.IsNullOrWhiteSpace(domain))
                domain = _settings.Domain;
            if (!secure.HasValue)
                secure = _settings.IsSecure;
            
            var curExp = span.HasValue && span.Value.Ticks > 0 && isSession != true && !maxAgeInSeconds.HasValue ?  DateToUTC(span.Value) : "";            
            
            List<string> keyvals = new List<string>();
            keyvals.Add($"{key}={value}");
            keyvals.Add($"expires={curExp}");
            keyvals.Add($"path={path}");
            if(!string.IsNullOrWhiteSpace(domain))
                keyvals.Add($"domain={domain}");
            if(secure.HasValue && secure.Value)
                keyvals.Add("secure");
            if (maxAgeInSeconds.HasValue && isSession != true)
            {
                keyvals.Add($"max-age={maxAgeInSeconds.Value}");
            }
            if (sameSite.HasValue){
                DescriptionAttribute desc = (DescriptionAttribute) typeof(SameSite).GetMember(sameSite.Value.ToString()).First().GetCustomAttributes(typeof(DescriptionAttribute), false).First();
                keyvals.Add($"samesite={desc.Description}");
            } 
            string cookieToSet = string.Join(";", keyvals);
            if (partitioned == true){
                cookieToSet += ";partitioned";
            }
            
            await SetCookie(cookieToSet);
        }

        public async Task RemoveAsync(string key,string path = null)
        {
            if (string.IsNullOrWhiteSpace(path))
                path = _settings.Path;
            List<string> keyvals = new List<string>();
            keyvals.Add($"{key}=");
            keyvals.Add($"Path={path}");
            keyvals.Add($"expires=Thu, 01 Jan 1970 00:00:01 GMT;");
            await SetCookie(string.Join(";", keyvals));
        }

        public async Task<T> GetValueAsync<T>(string key) where T : class
        {
            var res = await GetValueAsync(key);
            if (res == null)
                return default(T);
            return JsonConvert.DeserializeObject<T>(res);
        }
        public async Task<string> GetValueAsync(string key)
        {
            var cValue = await GetCookie();
            if (string.IsNullOrEmpty(cValue)) return null;                

            var vals = cValue.Split(';');
            foreach (var val in vals)
                if(!string.IsNullOrEmpty(val) && val.IndexOf('=') > 0)
                    if(val.Substring(0, val.IndexOf('=')).Trim().Equals(key, StringComparison.OrdinalIgnoreCase))
                        return val.Substring(val.IndexOf('=') + 1);
            return null;
        }

        private async Task SetCookie(string value)
        {
            await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \'{value}\'");
        }

        private async Task<string> GetCookie()
        {
            return await JSRuntime.InvokeAsync<string>("eval", $"document.cookie");
        }
        private static string DateToUTC(TimeSpan span) => DateTime.Now.Add(span).ToUniversalTime().ToString("R");
    }
}


//we also have this enum used in cookie handler class above

using System.ComponentModel;

namespace AltairCA.Blazor.WebAssembly.Cookie.Models;

public enum SameSite {
    
    [Description("lax")]
    Lax = 0,

    [Description("strict")]
    Strict = 1,

    [Description("none")]
    None = 2
    
}
 
 


The MDN article details a lot around cookies and there are a lot of way of controlling these cookies via attributes. Most browsers limit Cookie sizes to be 4 kilobytes maximum length (4096 bytes) of all cookies on a server. And a maxiumum of 50 cookies, still must be below the 4 kB limit. https://stackoverflow.com/a/4604212 We set up the cookie handling via Program.cs of a Blazor WASM like this :

Implementation for cookie handling for Blazor.wasm, AltairCABlazorCookieUtil.cs

 

builder.Services.AddAltairCACookieService(options =>
{
    options.DefaultExpire = TimeSpan.FromMinutes(15);
});




This extension method on IServiceCollection adds the cookie handling as a singleton service, AltairCABlazorCookieUtil.cs

 

using AltairCA.Blazor.WebAssembly.Cookie.Models;
using Microsoft.Extensions.DependencyInjection;

namespace AltairCA.Blazor.WebAssembly.Cookie.Framework;

public static class PipelineExtension
{
    public static IServiceCollection AddAltairCACookieService(this IServiceCollection services,Action<AltairCABlazorCookieConfigOptions> configure)
    {
        services.Configure(configure);
        services.AddSingleton<IAltairCABlazorCookieUtil, AltairCABlazorCookieUtil>();
        return services;
    } 
}

//note - the extension method above also uses this model class to set up default options for cookies 

namespace AltairCA.Blazor.WebAssembly.Cookie.Models;

public class AltairCABlazorCookieConfigOptions
{
    public TimeSpan DefaultExpire { get; set; } = TimeSpan.Zero;
    public string Path { get; set; } = "/";
    public string Domain { get; set; } = string.Empty;
    public bool IsSecure { get; set; } = false;
}



As can be seen in the implementation, these default config options are injected in the constructor via :

AltairCABlazorCookieUtil.cs - constructor parameter injecting the options which was set via services.Configure in the extension method of the pipeline

 
public AltairCABlazorCookieUtil(IJSRuntime jsRuntime,IOptions<AltairCABlazorCookieConfigOptions> options)
{
	JSRuntime = jsRuntime;
    _settings = options.Value;
}

As we can see, we remove the cookie by setting it to expire at Unix Epoch zero (1970, 1st of January) in the cookie handling. A good util to inspect Cookies and even edit them are available in this Google plugin: Edit this Cookie




Counter.razor - using the Cookie util in Blazor WASM sample app

 
 
 @inject IAltairCABlazorCookieUtil _cookieUtil;
 
  
 
 
private async Task IncrementCount()
    {
        currentCount++;
        Content = await _cookieUtil.GetValueAsync("c");
        ContentObj = await _cookieUtil.GetValueAsync<object>("d");

        await _cookieUtil.SetValueAsync("c", "this is cookie with key c");
        await _cookieUtil.SetValueAsync("d", new
        {
            hello = "hello world. i am a cookie with key d"
        });
        await _cookieUtil.SetValueAsync("cookieWithSameSiteSet", "Cookie which specified cross site request inclusion of the cookie : SameSite value (lax | strict | none)", sameSite: SameSite.Lax);

        await _cookieUtil.SetValueAsync("cookiePartitioned", "Partitioned cookie", partitioned: true);
     
        await _cookieUtil.SetValueAsync("cookieWithMaxAge", "Max age cookie", maxAgeInSeconds: 600);

        await _cookieUtil.SetValueAsync("cookieWhichIsToBeSetToSessionCookie", "Session cookie = temporal cookie", isSession: true);

    }
  
One important note about the cookie util here, observe the usage of the 'eval' method to set the cookie via Js in the util class and also retrieve cookies :

Implementation for cookie handling for Blazor.wasm, AltairCABlazorCookieUtil.cs

 
 
   private async Task SetCookie(string value)
        {
            await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \'{value}\'");
        }

        private async Task<string> GetCookie()
        {
            return await JSRuntime.InvokeAsync<string>("eval", $"document.cookie");
        }
 
 


Using 'eval' we let Js run the Js code we pass in here in Blazor WASM app. This also means that we cannot write HttpOnly cookies, since we rely fully on Js here.

As some of you know, third party cookie support are planned by Chrome to be discontinued in support. The following article is interesting reading about this. https://itrust-digital.com/cookieless-future/