razor-pages - ASP.NET Core 3.1 Razor 页面 : How to automatically redirect to Login page from Index page?

标签 razor-pages asp.net-core-3.1

我正在使用 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/

相关文章:

c# - 绑定(bind)项目重置时,Core.NET 选择列表不会在回发时重置

c# - 如何在多个页面重用部分模型

c# - 自动将 JWT 加载到 User.Identity (ASP.NET Core 3.1)

dependency-injection - 某些服务无法使用库 : NetCore. AutoRegisterDi 构建

c# - Razor 页面运行时编译不起作用

c# - 有没有办法以相应的形式显示错误?

c# - 通过依赖注入(inject)获取 dbcontexts 背后的 10 多个 razor 页面代码

routes - .net core 根据当前域名路由到 Razor 页面区域?

c# - 如何在 dotnet core 3 中使用依赖项在启动时调用自定义服务?

c# - 无法启动 Base!/app/.local-chromium/Linux-706915/chrome-linux/chrome : . .. libX11.so.6