Need to read a cookie in blazor server mainlayout.cs

35 Views Asked by At

I need to get a cookie within my MainLayout.razor.cs OnInitializedAsync() and save it in a scoped service.

I have tried going the middleware route by getting it from the HTTP context and stuffing it into a scoped service. This works, but my scoped services keep going away for some strange reason. This has to be done in the OnInitializedAsync method for reasons I won't go into.

The bottom line is I need to get the cookies.

Suggestions?

1

There are 1 best solutions below

1
Qiang Fu On

You could add following code to bottom of mainlayout.razor

@code{
    [CascadingParameter]
    public HttpContext? httpContext { get; set; }
    protected override void OnInitialized()
    {
        if (httpContext != null)
        {
            var cookies = httpContext.Request.Cookies;
        }
    }
}

Test
enter image description hereenter image description here