You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 2.1 Razor Pages如何取消全局认证,开放首页等匿名访问

.NET Core 2.1 Razor Pages 认证逻辑调整方案

1. 取消全局强制认证

打开Startup.cs,找到ConfigureServices方法。若存在全局授权过滤器(强制所有页面需认证),移除该配置:

原全局授权配置(可能存在):

services.AddMvc(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

修改后(移除全局强制认证):

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

2. 精准控制页面授权

  • 对需登录访问的页面,在对应PageModel类上添加[Authorize]特性:
    [Authorize]
    public class SecurePageModel : PageModel
    {
        public void OnGet()
        {
        }
    }
    
  • 若你保留了全局授权策略(不推荐),则在允许匿名的页面(如首页IndexModel)的类上添加[AllowAnonymous]特性:
    [AllowAnonymous]
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
        }
    }
    

3. 添加手动触发的登录按钮

根据你使用的Microsoft认证类型,选择以下方式实现:

方式一:直接跳转登录页面

在首页或导航的cshtml文件中添加登录链接:

<a asp-page="/Account/Login" class="btn btn-primary">登录</a>

方式二:触发认证挑战(适用于OpenID Connect/Microsoft身份认证)

在首页IndexModel中添加登录处理方法:

public IActionResult OnPostLogin()
{
    var redirectUrl = Url.Page("/Index");
    return Challenge(
        new AuthenticationProperties { RedirectUri = redirectUrl },
        OpenIdConnectDefaults.AuthenticationScheme);
}

再在首页cshtml中添加登录按钮表单:

<form method="post" asp-page-handler="Login">
    <button type="submit" class="btn btn-primary">登录</button>
</form>

4. 验证配置

启动项目后,确认首页及允许匿名的页面无需跳转登录;点击登录按钮后可正常跳转到Microsoft登录页,登录完成后能访问带[Authorize]的页面。

内容的提问来源于stack exchange,提问作者Jio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:25:12