Calling a Razor page action

When a Blazor Server-Side App is generated in VS2019 with individual user account authentication the following code is created:

<form method="post" action="Identity/Account/LogOut">
        <button type="submit" class="nav-link btn btn-link">Log out</button>
    </form>

Here we have a button that logs the user out. I want to call this same action from my own function but I do not know how to post to a razor page. How can I do that?

Upvotes: 1

Views: 1203

Answers (1)

Umair
Umair

Reputation: 5481

You can navigate to the page using NavigationManager

See this example code:

@inject NavigationManager NavigationManager

<button class="btn btn-primary" @onclick="Logout">
    Logout
</button>

@code {
    private void Logout()
    {
        NavigationManager.NavigateTo("/Identity/Account/LogOut", true);
    }
}

And in the \Areas\Identity\Pages\Account\LogOut.cshtml page you will either need to change the OnPost to OnGet or add OnGet method as below:

public async Task<IActionResult> OnGet()
{
    if (SignInManager.IsSignedIn(User))
    {
        await SignInManager.SignOutAsync();
    }

    return Redirect("~/");
}

Thanks to Henk Holterman as he stated, you will need to set forceRelead parameter true in NavigationManager.NavigateTo("...", true)

Upvotes: 4

Related Questions