使用 ASP.NET Identity,如果我想构造一个链接到登录页面的
<a>
元素,我可以使用 Razor Helpers 和一些魔术字符串:
<a asp-area="Identity" asp-page="/Account/Login">Login</a>
(不是手头的问题,但如果有人能告诉我为什么这个复杂的魔术字符串集合在某种程度上比硬编码“/Identity/Account/Login”相对 URL 更好,我会很高兴。)
我的问题是:如果我想从处理程序例程(即剃刀页面后面的 C# 代码)返回重定向,是否有一些推荐的魔法可以用来获取登录页面的相对 URL?
换句话说,还有比以下更好的吗:
return Redirect("/Identity/Account/Login");
这样使用:
return RedirectToPage("/Account/Login", new { area = "Identity" });
您可能缺少 RazorPages。根据您的程序中映射的方式。cs,或者添加到您的 Web.config
services.AddRazorPages;
或在您的.Net6 Programs.cs中使用
builder.Services.AddRazorPages;
或者如果您使用端点,请替换
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
与
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
OP在这里。这就是我最后的结局。
假设
Obj
是我的表单数据,val
是表单中某些文本的标签,在我的[Get] Create
方法中,我有:
public IActionResult Create()
{
// if session data for val is set, get the val and create a new Obj
if (!HttpContext.Session.GetString(SessionKeyObjVal).IsNullOrEmpty())
{
Obj prepopulatedObj = new Obj()
{
val = HttpContext.Session.GetString(SessionKeyObjVal)
};
// reset session data to empty after use
HttpContext.Session.SetString(SessionKeyDescription, "");
// return view with fields populated based on session data
return View(prepopulatedObj);
}
return View();
}
在我的
[Post] Create
方法中我有:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Obj obj)
{
// if not authenticated, set session data for val and redirect to login
if (!HttpContext.User.Identity.IsAuthenticated)
{
HttpContext.Session.SetString("val", Obj.val);
return RedirectToPage("/Account/Login", new { area = "Identity" });
}
etc...
这有效!!!!但是,因为我没有在
[Authorize]
方法上使用 Post
,所以用户在登录后会被重定向到主页。如果有人有其他方法,请告诉我。我想不出任何方法来确保用户在这种特定情况下登录后被带到Create
页面