所以,我有一个看起来像这样的应用程序:
Pages
├─Restricted
│ ├─Index
│ └─SecretPage
├─Index
└─UserPage
Index
页面允许匿名访问并具有登录表单,UserPage
页面可以由任何经过身份验证的用户访问,Restricted
文件夹中的页面只能由授权用户访问。 / p>
未经身份验证的用户可能会尝试访问UserPage
页面或Restricted
文件夹中的页面,但随后它们将被重定向到Index
页面(在根目录中)以登录。在这种情况下,URL将类似于https://example.com/?returnUrl=UserPage
或https://example.com/?returnUrl=Restricted
。
要在登录后将用户重定向到他们想去的地方,我有以下代码:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
var redirectTarget = string.Empty;
// try to authenticate the user
if (/* the log in attempt is successful */)
{
// do the log in stuff; i.e., Claims and SignInAsync
redirectTarget = string.IsNullOrWhiteSpace(returnUrl) ? "UserPage" : returnUrl;
}
return RedirectToPage(redirectTarget);
}
只要returnUrl
是一页,此方法就可以正常工作;但是,当returnUrl
是文件夹时;例如Restricted
,它将引发“ InvalidOperationException:没有名为'/ Restricted'的页面与提供的值匹配。”
因此,我切换到Redirect(redirectTarget)
,但是如果Index/UserPage
为UserPage
或为空,那么这个错误地将用户重定向到returnUrl
而不是null
。另外,这意味着我需要对登录名/当前页面URL进行硬编码。即/
,而不是像RedirectToPage
那样,在尝试登录失败的情况下,不必依靠重定向方法将用户重定向到同一页面。
我可以使用UserPage
而不是/UserPage
解决重定向到UserPage
的问题;即在其前面加上/
。但是,这意味着该网站不能托管在虚拟目录中,因为UserPage
不在网站的根目录中。
有什么干净的方法可以进行这种重定向吗?
P.S。该应用程序使用在.NET Core 2.2上运行的ASP.NET Core 2.2。