How to redirect to a page after logged-in?

Dondon510 221 Reputation points
2022-09-30T18:25:07.227+00:00

Hi All,

I have a use case like below:

I send an email with a link:

blah blah blah, to see sales info, click this link (ie https://example.com/salesinfo/10)

when it clicked, it will bring the user to the salesinfo page, but if they haven't login yet, they need to login and they would brought to salesinfo page as soon as they logged-in.

Controller:

 [Authorize]  
public class SalesController : Controller  
{  
    [HttpGet]  
    [Route("/SalesInfo/{id}")]  
    public async Task<IActionResult> Index(string id)  
    {  
      

     }  
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,138 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Laxmikant 216 Reputation points
    2022-10-01T00:48:55.187+00:00

    when you redirect to login page

    Response.Redirect("loginpage?returnurl=" + Server.UrlEncode(Request.Url.AbsoluteUri));  
    

    after login validation successful

    if (!string.IsNullOrEmpty(ReturnUrl))    
    {    
        Response.Redirect(ReturnUrl);    
    }    
    else    
    {    
        Response.Redirect("homepageurl");    
    }   
    
     
    
    0 comments No comments

  2. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2022-10-03T05:33:32.057+00:00

    Hi @Dondon510 ,

    When using asp.net core Identity, we could use the following code to configure the login page:

    builder.Services.ConfigureApplicationCookie(options =>  
    {  
        // Cookie settings  
        options.Cookie.HttpOnly = true;  
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);  
      
        options.LoginPath = "/Identity/Account/Login";  //set the login page.  
        options.AccessDeniedPath = "/Identity/Account/AccessDenied";  
        options.SlidingExpiration = true;  
    });  
    

    Then, when we want to access the protected page without login, it will redirect to the login page with the ReturnUrl parameter. Like this:

    246865-1.gif

    So, in the Login Post method, you can add a returnUrl parameter to receive the return url, and then use the LocalRedirect method to redirect to the returnurl. Refer to the following code:

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)  
        {  
            returnUrl ??= Url.Content("~/");  
    
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();  
    
            if (ModelState.IsValid)  
            {  
                // This doesn't count login failures towards account lockout  
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true  
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);  
                if (result.Succeeded)  
                {  
                    _logger.LogInformation("User logged in.");  
                    return LocalRedirect(returnUrl);  
                }  
                if (result.RequiresTwoFactor)  
                {  
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });  
                }  
                if (result.IsLockedOut)  
                {  
                    _logger.LogWarning("User account locked out.");  
                    return RedirectToPage("./Lockout");  
                }  
                else  
                {  
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");  
                    return Page();  
                }  
            }  
    
            // If we got this far, something failed, redisplay form  
            return Page();  
        }  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


  3. Alexy 0 Reputation points
    2023-12-17T11:44:15.31+00:00

    here are two approaches you can take to achieve your desired behavior:

    1. Using the ReturnUrl Parameter:

    1. In your SalesInfo controller action:
      • Add a string parameter called returnUrl to the Index method:
    [Authorize]
    public class SalesController : Controller
    {
        [HttpGet]
        [Route("/SalesInfo/{id}")]
        public async Task<IActionResult> Index(string id, string returnUrl)
        {
            // ... your existing logic ...
    
            return View();
        }
    }
    
    
    
    
    
    
    [HttpPost]
    [Route("/User/Login/")]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(Views.User.Login login, string returnUrl)
    {
        // ... your existing validation logic ...
    
        if (result.Succeeded)
        {
            // Check if returnUrl is available
            if (!string.IsNullOrEmpty(returnUrl))
            {
                // Redirect to the saved returnUrl
                return LocalRedirect(returnUrl);
            }
            else
            {
                // Redirect to a default page (e.g., Home)
                return LocalRedirect("~/Home/");
            }
        }
    
        // ... other cases ...
    }
    
    **In your custom login controller:**
    
    
    
    
    
    • Check if the Request.QueryString contains a parameter named returnUrl. If so save it in a variable
    0 comments No comments