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

.NET Core中IAuthenticationFilter等效的认证实现方法

.NET Core 实现原IAuthenticationFilter身份认证逻辑方案

报错原因

你遇到的CS7069错误是因为.NET Core完全移除了旧版System.Web下的ASP.NET类型体系,.NET Framework中使用的IAuthenticationFilter、HttpContextBase、旧版ActionFilterAttribute等类型都已不存在,过滤器管道做了全量重新设计,不需要硬套旧接口,实现IAsyncAuthorizationFilter即可完成完全一致的认证逻辑。
授权过滤器是.NET Core MVC过滤器管道中执行优先级最高的过滤器类型之一,早于普通Action过滤器执行,完全满足“访问控制器动作前先完成身份校验”的需求。

前置配置:启用Session

你的原有逻辑依赖Session存储登录状态,使用前需要先在项目中完成Session配置(.NET 6+ Program.cs):

  • 先安装Microsoft.AspNetCore.Session NuGet包
  • 注册服务并配置中间件,注意中间件顺序不能错:
// 注册Session服务
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});
// 注册MVC控制器/视图服务
builder.Services.AddControllersWithViews();

var app = builder.Build();

// 中间件顺序:UseSession必须放在UseRouting之后、UseAuthorization和路由映射之前
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

自定义认证过滤器实现

直接实现IAsyncAuthorizationFilter接口,逻辑和你原有.NET Framework代码完全对应,同时补充匿名访问跳过逻辑,避免登录页死循环:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

// 标记为特性,可直接打在控制器/动作上
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthenticationFilter : Attribute, IAsyncAuthorizationFilter
{
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        // 跳过标记了[AllowAnonymous]的动作/控制器,比如登录、注册页
        if (context.ActionDescriptor.EndpointMetadata.Any(m => m is IAllowAnonymousFilter))
        {
            return;
        }

        // 对应旧逻辑OnAuthentication:校验Session中的用户名
        string? username = context.HttpContext.Session.GetString("Username");
        if (string.IsNullOrEmpty(username))
        {
            context.Result = new UnauthorizedResult();
        }

        // 对应旧逻辑OnAuthenticationChallenge:未授权则跳转登录页
        if (context.Result == null || context.Result is UnauthorizedResult)
        {
            context.Result = new RedirectToActionResult("Login", "Account", null);
        }
        await Task.CompletedTask;
    }
}

过滤器注册方式

你可以根据需求选择不同的注册范围:

  • 全局注册:所有控制器动作默认都需要认证,不需要额外注册服务
builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<CustomAuthenticationFilter>();
});
  • 控制器/动作级注册:仅指定范围生效,需要先将过滤器注入DI容器
// 先在Program.cs注册过滤器
builder.Services.AddScoped<CustomAuthenticationFilter>();
  • 控制器级示例:
[ServiceFilter(typeof(CustomAuthenticationFilter))]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
  • 动作级示例:
public class UserController : Controller
{
    [ServiceFilter(typeof(CustomAuthenticationFilter))]
    public IActionResult UserCenter()
    {
        return View();
    }
}

补充说明

  • 不需要认证的动作(比如登录接口),直接打上内置的[AllowAnonymous]特性即可跳过校验,示例:
public class AccountController : Controller
{
    [AllowAnonymous]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public IActionResult Login(string username, string password)
    {
        // 你的密码校验逻辑
        if (校验通过)
        {
            // 登录成功写入Session
            HttpContext.Session.SetString("Username", username);
            return RedirectToAction("Index", "Home");
        }
        ModelState.AddModelError("", "用户名或密码错误");
        return View();
    }
}
  • 如果是WebAPI项目不需要页面跳转,直接移除跳转逻辑,保留context.Result = new UnauthorizedResult();即可,接口会自动返回401状态码。
  • 如果后续需要更复杂的认证能力(比如角色校验、策略授权、第三方登录),更推荐使用.NET Core内置的认证授权中间件(Cookie认证、JWT认证等),和框架原生能力兼容性更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:45:46