asp.net-mvcasp.net-coreasp.net-identity

How to redirect from an Asp.Net Core MVC controller to a login page written in Razor page


I am new to Asp.Net Core MVC. I have created an MVC application in .Net Core 6.0. When I scaffolded the Identity, it created it in Razor pages. Once the user enters the login credentials, the Login Razor page checks whether any additional information needed to be provided by the user. if so, it redirects to an MVC controller. After this information is saved in the database, I have to redirect the user back to the login page.

[HttpPost]
public IActionResult SecretQuestionSetup(SecretQuestionVM secretQuestionVM)
{
   if (ModelState.IsValid)
   {
      //code to save data in the db
     
   }

   return RedirectToAction("Identity/Account/Login");
 
}

It is trying to redirect to: https://localhost:7281/MyController/Identity%2FAccount%2FLogin As you can see it includes the controller name, "MyController" as part of the URL. If the redirect URL is https://localhost:7281/Identity/Account/Login, then it would have worked. I tried to add the following code in the Program.cs, still it didn't fix it.

builder.Services.ConfigureApplicationCookie(options =>
{
   options.LoginPath = "/login";
});

Solution

  • In MVC Controller if you want to redirect to Razor Pages, the RedirectToAction is not chosen as it is returning the result to a specified controller and action method https://dotnettutorials.net/lesson/redirect-redirecttoaction-mvc/ .

    Configuration in Program.cs is not necessary. You need to change the method.

    [HttpPost]
    public RedirectResult SecretQuestionSetup(SecretQuestionVM secretQuestionVM)
    {
       if (ModelState.IsValid)
       {
          //code to save data in the db
         
       }
    
       return Redirect("/Identity/Account/Login");
     
    }
    

    enter image description here