3per
3per

Reputation: 384

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

Upvotes: 0

Views: 78

Answers (1)

agua from mars
agua from mars

Reputation: 17434

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

Upvotes: 1

Related Questions