(C# ASP.NET Core) SignOutAsync with Tag Helpers

Following is a brief scheme on signing out a logged-in user. A function for sign-out is written in the same file as for the login code. Then this function is called from the click of some anchor link and "SignOutAsync" called to kill the login cookie. Finally, a redirection is done to the login page.
(Rev. 19-Mar-2024)

Categories | About |     |  


How does SignOut take place?

Step 1: First create a function for Sign out

The function can be created in the login page to keep it close to the login code.

But this function will be called from another page - possibly deep inside some "Area" folder. So this function will have to be connected to the click of some anchor tag helper, which is technically a GET request. Hence the name should be prefixed with OnGet

// the name of the function is prefixed 
// with OnGet because this function will be 
// called from a click of some anchor 
// tag helper 
public async Task<IActionResult> OnGetSignOut()

  // code here 

  // redirection to login page 

Step 2: Call the SignOut function to sign the user out.

// built-in function for sign out 
// kills the login cookie 
await HttpContext.SignOutAsync(

// NOTE: CookieAuthenticationDefaults.AuthenticationScheme 
// is a fixed constant "Cookies". the constant MUST be 
// passed as a parameter 

Step 3: Use LocalRedirect to redirect the user to the login page or to the website home page.

The completed code is shown below.

public async Task<IActionResult> OnGetSignOut()

  // kills the login cookie 
  await HttpContext.SignOutAsync(

  // redirect to web home or login page 
  return LocalRedirect("/");


Video Explanation

Please watch the following youtube video:

How is Click connected?

The above function is to be called from the click of some anchor tag helper. Following is an example markup:

// it is assumed that the  
// function OnGetSignOut is written 
// in the backing class "Login.cshtml.cs" 

// this mark-up is on, say, a header strip  
// of some razor page 

<div class="navbar-nav">

    <div class="nav-item text-nowrap">

      <a  asp-page-handler="SignOut" asp-page="Login">Sign out</a>



This Blog Post/Article "(C# ASP.NET Core) SignOutAsync with Tag Helpers" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.