Search code examples
c#asp.net-coreasp.net-core-identity

.NET Core Identity Login Page handler OnGetAync()


I working on a .NET Core 3.1 project using Identity. On the Login.cs.html page, the OnGetAsync() page handler is as follows:

public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    returnUrl = returnUrl ?? Url.Content("~/");

    // Clear the existing external cookie to ensure a clean login process
    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
        .ToList();

    ReturnUrl = returnUrl;
}

I'm a bit confused about the line of code returnUrl = returnUrl ?? Url.Content("~/"); and why it is written this way. Why is it checking if returnUrl is null, won't it always be null? Why not remove the string returnUrl = null as a method parameter and assign ReturnUrl = Url.Content("~/");? Am I missing some thing here?


Solution

  • The returnUrl parameter has been set up to use an optional argument:

    If no argument is sent for that parameter, the default value is used.

    With the default setup for Identity, the value for returnUrl comes from the query-string of the request URL. For example, the following URL provides a value for the returnUrl argument:

    /Identity/Account/Login?returnUrl=/Some/Protected/Route
    

    In this case, returnUrl will not be null. However, consider the following URL:

    /Identity/Account/Login
    

    In this case, returnUrl will be null. There's no URL to redirect to after the login process completes, so the line you've called out will set it to Url.Content("~/"). That just means it'll end up redirecting the user to the root of the web application, which is typically the home page.