Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Pascal R. Avatar asked Dec 03 '22 18:12

Pascal R.


1 Answers

If you scaffolded Identity and overridden the old "LogOut.cshtml" from when you created the project via template, the Logout button won't logout. Assume you've used the default IdentityUser model. I ran into this issue and just wanted to add this if anyone else had this problem as well. I'm using Blazor Server with .Net 5.0.3's template. You can remove the Logout.cshtml.cs after as well.

Replace this \Areas\Identity\Pages\Account\LogOut.cshtml

@page
@model LogoutModel
@{
    ViewData["Title"] = "Log out";
}

<header>
    <h1>@ViewData["Title"]</h1>
    @{
        if (User.Identity.IsAuthenticated)
        {
            <form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Page("/", new { area = "" })" method="post">
                <button type="submit" class="nav-link btn btn-link text-dark">Click here to Logout</button>
            </form>
        }
        else
        {
            <p>You have successfully logged out of the application.</p>
        }
    }
</header>

Replace with

@page
@using Microsoft.AspNetCore.Identity
@attribute [IgnoreAntiforgeryToken]
@inject SignInManager<IdentityUser> SignInManager
@functions {
    public async Task<IActionResult> OnPost()
    {
        if (SignInManager.IsSignedIn(User))
        {
            await SignInManager.SignOutAsync();
        }

        return Redirect("~/");
    }
}
like image 106
MichaelTran Avatar answered Dec 09 '22 13:12

MichaelTran