.NET Core 身份登录页面处理程序 OnGetAync()

.NET Core Identity Login Page handler OnGetAync()

我正在使用 Identity 开发 .NET Core 3.1 项目。在Login.cs.html页面上,OnGetAsync()页面处理程序如下:

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;
}

我对代码行 returnUrl = returnUrl ?? Url.Content("~/"); 以及为什么这样写感到有点困惑。为什么要检查 returnUrl 是否为 null,它不会总是 null 吗?为什么不删除 string returnUrl = null 作为方法参数并分配 ReturnUrl = Url.Content("~/");?我在这里错过了什么吗?

returnUrl 参数已设置为使用 optional argument:

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

对于身份的默认设置,returnUrl 的值来自请求 URL 的查询字符串。例如,以下 URL 为 returnUrl 参数提供了一个值:

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

在这种情况下,returnUrl 而不是 null。但是,请考虑以下 URL:

/Identity/Account/Login

在这种情况下,returnUrl 将是 null。登录过程完成后没有 URL 可重定向到,因此您调用的行会将其设置为 Url.Content("~/")。这只是意味着它最终会将用户重定向到 Web 应用程序的根目录,通常是主页。