我正在使用 ASP.NET Core 3.1 MVC 和 Razor 页面构建 Web 应用程序。
我是 Razor 页面的新手。
我使用上面的方法创建了一个基本应用程序。我想在应用程序启动时加载登录页面,但是 Index.cshtml 页面似乎是起始页。
为了从 Index.cshtml 页面(起始页)重定向到我的 Login.cshtml 页面,我在 Index.cshtml 页面模型中执行了以下操作。但它不起作用。
已编辑:
索引.cshtml:
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<form method="get" asp-page="Index" hidden name="myForm">
<input type="submit" name="submit" value="Redirect 1" asp-page-handler="Redirect1" hidden />
</form>
</div>
Index.cshtml.cs:
public class IndexModel : PageModel
{
public IndexModel()
{
OnPostRedirect1();
}
public void OnGet() {}
public IActionResult OnPostRedirect1()
{
return RedirectToPage("Login");
}
}
如何从索引页自动重定向到登录页?
最佳答案
您有一些选择。如果您不希望未经授权的用户访问索引页面,请将 [Authorize]
属性应用于 PageModel 类:
[Authorize]
public class IndexModel : PageModel
{
...
}
然后,如果你的登录页面不在/account/login
,在Startup中配置登录页面:
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/YourLoginPage";
});
框架会自动将未经身份验证的用户重定向到登录页面。这是大多数人可能会做的事情。或者,如果您根本不需要索引,请将其删除并通过更改其路由模板将登录页面设置为主页:
@page "/"
这将根据其文件路径覆盖页面的常规路由:https://www.learnrazorpages.com/razor-pages/routing#override-routes
关于razor-pages - ASP.NET Core 3.1 Razor 页面 : How to automatically redirect to Login page from Index page?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63326115/