Search code examples
asp.net-coreblazorblazor-server-side

How to sign out over HttpContext in server-side Blazor


I access the HttpContext in a Blazor server-side view to manually log out. I added this line to Startup.cs: services.AddHttpContextAccessor(); and inject it in the view with @inject IHttpContextAccessor HttpContextAccessor. I've got a log out button which tries to execute this code:

await HttpContextAccessor.HttpContext.SignOutAsync("Cookies");

but I get the following error message:

System.InvalidOperationException: 'Headers are read-only, response has already started.'

How can I prevent this error?


Solution

  • This tripped me up too, but you need the logout functionality to be on a Razor Page (not a Blazor component). Create a Logout page and put your logout code in the OnGetAsync() method.

    Your logout button can then link to the logout page.

    http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/4316/A-Demonstration-of-Simple-Server-side-Blazor-Cookie-Authentication.aspx - this is a helpful example