Search code examples
c#asp.net-corecookiesblazor-server-side

Creating and Reading Cookies on Blazor Server Side


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.


Solution

  • 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);
            }
        }
    }