aspdotnet core with identity logout call from ajax does not log user out

26 Views Asked by At

I am trying to use ajax to post from a link to log a user out using the identity pages.

The page model function I'm calling from ajax is in Logout.cshtml.cs (scaffolded and unmodified):

public async Task<IActionResult> OnPost(string returnUrl = null)
{
    await _signInManager.SignOutAsync();
    _logger.LogInformation("User logged out."); //I see this output
    if (returnUrl != null)
    {
        return LocalRedirect(returnUrl); //this line gets executed
    }
    else
    {
        // This needs to be a redirect so that the browser performs a new
        // request and the identity for the user gets updated.
        return RedirectToPage();
    }
}

I post to this with ajax like so:

$('#submitLogout').on("click", function (e) {
        alert("jquery: Clicked Logout!");
        PostLogout();
        alert("out of Ajax and back to link click function.")
        window.location.href = '@Url.Action("Home","Index")'
});

function PostLogout() {
    alert("Ajax POST executing . . . ");
    $.ajax({
        type: "POST",
        url: "/Identity/Account/Logout",
        data: { returnUrl: '@Url.ActionLink("Index", "Home")'},
        headers: {
            RequestVerificationToken: $(
                'input:hidden[name="__RequestVerificationToken"]'
            ).val()
        },
        success: function () {
            alert("success in Ajax");
            return false;
        }
    });
}

I have verified that the page OnPost handler is being called (with a breakpoint and from the logger information in the console), but my user stays logged in. If I return false from the jquery function I end up with the standard logout page and can click here to logout successfully (right outcome but have to click two logout links). My ajax success function never gets called.

my link code looks like this:

<a class="nav-item" id="submitLogout" href="/Identity/Account/Logout">Logout</a>
@Html.AntiForgeryToken()

I can use a form submit button and get the behavior I want, but the button never looks the same as just a link (font size is always a little bit different) thus my current attempt to post from a link. This is the form submit button that works:

<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout"
    asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
    <button type="submit" class="nav-item btn-pgdBanner" style="color: var(--color5)">Logout</button>
</form>

I'm not sure if I can get this to work the way I want, so will end up using the standard post from an inline form to logout, but wonder if there is something fairly simple that I'm just missing?

0

There are 0 best solutions below