C
C#2y ago
no >> body

OnAppendCookie callback doesn't work

I have an ASP.NET Core project, which uses IdentityServer4. In my configuration I have CookiePolicyOptions which contains the next setup:
services.Configure<CookiePolicyOptions>(
option =>
{
option.MinimumSameSitePolicy = SameSiteMode.None;
option.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always;
option.OnAppendCookie = cookieContext =>
{
Console.WriteLine("Cookie appended: " + cookieContext.CookieName);
};
option.OnDeleteCookie = context =>
{
Console.WriteLine("Cookie deleted: " + context.CookieName);
};
});
services.Configure<CookiePolicyOptions>(
option =>
{
option.MinimumSameSitePolicy = SameSiteMode.None;
option.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always;
option.OnAppendCookie = cookieContext =>
{
Console.WriteLine("Cookie appended: " + cookieContext.CookieName);
};
option.OnDeleteCookie = context =>
{
Console.WriteLine("Cookie deleted: " + context.CookieName);
};
});
For some reason, I can't reach the code from the OnAppendCooie and OnDeleteCookie. I've also added a custom filter to append a new cookie to the response. The behavior was still the same - OnAppendCookie and OnDeleteCookie were not called.
2 Replies
no >> body
no >> body2y ago
My filter looks like this
public class MyCustomFilter : ResultFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Cookies.Append("MyCustomCookie", "Blah-Blah");
base.OnResultExecuting(context);
}
}
public class MyCustomFilter : ResultFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Cookies.Append("MyCustomCookie", "Blah-Blah");
base.OnResultExecuting(context);
}
}
and registration
services.AddControllersWithViews(c =>
{
c.Filters.Add(new MyCustomFilter());
});
services.AddControllersWithViews(c =>
{
c.Filters.Add(new MyCustomFilter());
});
no >> body
no >> body2y ago
Am I missing something? I thought it should trigger when every cookie appends The example application https://github.com/ihordyrman/CookieTest/blob/main/Program.cs Alright, I found the reason. It requires an additional middleware.
app.UseCookiePolicy();
app.UseCookiePolicy();
catfacepalm