Search code examples
c#blazorblazor-client-side

Set cookie at the monent when index.html downloading


I want to set a http cookie, when a client is downloading index.html.

context.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = new DateTimeOffset(DateTime.Now.AddDays(1)),
                HttpOnly = true,
                Secure = true,
                SameSite = SameSiteMode.Strict
            }); 

I have no idea where can I put it to the server code.

It is all about index.html on the server:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapFallbackToClientSideBlazor<Client.Program>("index.html");
        });

Solution

  • Add a middleware before app.UseBlazorFrameworkFiles and check the request path:

    app.Use((context, next) =>
    {
        if (PathIsApplicationPath(context.Request.Path))
        {
            SetApplicationCookie(context.Response);
        }
        return next();
    });
    app.UseBlazorFrameworkFiles();
    
    ...
    
    private bool PathIsApplicationPath(PathString path)
    {
         // TODO: implement this
    }
    
    private void SetApplicationCookie(HttpResponse response)
    {
        response.Cookies.Append("TheCookieName", "TheCookieValue", new CookieOptions
                {
                    Expires = new DateTimeOffset(DateTime.Now.AddDays(1)),
                    HttpOnly = true,
                    Secure = true,
                    SameSite = SameSiteMode.Strict
                });
    }