redirect using HttpContextAccessor

Michael P 20 Reputation points
2025-12-12T12:46:40.74+00:00

Hi,

I am trying to redirect to my login page on a condition using IHttpContextAccessor. Here is my code :

if (condition)

{

_signInManager.SignOutAsync();

_httpContextAccessor.HttpContext.Response.Redirect("/Identity/Account/Login");

}

But the redirect doesn't happen and the code continues. Am I using this incorrectly or is there another way to do this?

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Varsha Dundigalla(INFOSYS LIMITED) 3,885 Reputation points Microsoft External Staff
    2025-12-12T15:17:52.1466667+00:00

    Thank you for reaching out.

    The issue happens because Response.Redirect() only writes a redirect header; it doesn’t stop the rest of the code from running in ASP.NET Core. The correct way is to return a redirect result, which satisfies the IActionResult requirement and properly ends the request.

    Here’s the simple syntax you can use:

    return`` Redirect("/Identity/Account/Login");

    return`` RedirectToPage("Account/Login");

    return`` LocalRedirect(returnUrl);

    These methods are designed for controller actions and Razor Pages, so they work perfectly when your action returns IActionResult.

    For more details, you can check the official Microsoft docs:

    Please let us know if you require any further assistance, we’re happy to help.

    If you found this information useful, kindly mark this as "Accept Answer".

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.