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

在Action Filter中使用EF Core验证用户时遇SQL Server连接错误求助

解决SQL Server连接错误(错误26)的建议

针对你在自定义ActionFilter中实例化DBContext时遇到的SQL Server连接错误,以下是具体解决步骤:

1. 排查连接字符串配置

  • 确认appsettings.json(或传统项目的web.config)中的连接字符串参数:
    • 服务器/实例名是否正确:本地SQL Server Express通常为.\SQLEXPRESS或localhost\SQLEXPRESS;默认实例直接写机器名/IP。
    • 身份验证方式匹配:Windows认证用Trusted_Connection=True,SQL Server认证需指定User ID和Password。
    • 示例正确格式:
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=YourDBName;Trusted_Connection=True;TrustServerCertificate=True;"
      }
      
  • 确保DBContext正确读取连接字符串:在DBContext构造函数中注入配置,而非硬编码:
    public class DBContext : DbContext
    {
        private readonly IConfiguration _config;
        public DBContext(IConfiguration config) => _config = config;
    
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
        }
    }
    

2. 检查SQL Server服务与配置

  • 确认SQL Server服务运行:打开services.msc,找到对应实例的SQL Server服务,确保状态为正在运行。
  • 启用TCP/IP协议:打开SQL Server配置管理器,展开SQL Server网络配置→对应实例的协议,启用TCP/IP;进入TCP/IP属性,确认IP地址的TCP端口为1433(默认)且已启用。
  • 防火墙放行:本地防火墙需允许SQL Server的1433端口;远程服务器需同步配置防火墙规则。

3. 改用依赖注入实例化DBContext

直接new DBContext()不符合ASP.NET Core最佳实践,且容易引发配置问题,建议通过依赖注入获取:

  • 注册DBContext到服务容器(Program.cs):
    builder.Services.AddDbContext<DBContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
  • 注册过滤器为服务:
    builder.Services.AddScoped<UserValidationAttribute>();
    
  • 在过滤器中注入DBContext:
    public class UserValidationAttribute : ActionFilterAttribute
    {
        private readonly DBContext _dbContext;
        public UserValidationAttribute(DBContext dbContext) => _dbContext = dbContext;
    
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string objectId = context.HttpContext.User.Claims
                .FirstOrDefault(c => c.Type.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase))?.Value;
    
            if (!string.IsNullOrEmpty(objectId))
            {
                var user = _dbContext.UserB2cs.FirstOrDefault(r => r.B2cobjectId == objectId)?.User;
                // 后续验证逻辑
            }
        }
    }
    
  • 在Action上使用ServiceFilter标记:
    [ServiceFilter(typeof(UserValidationAttribute))]
    public IActionResult TargetAction()
    {
        // Action逻辑
    }
    

4. 验证连接有效性

  • 用SQL Server Management Studio(SSMS)使用相同连接参数测试连接,若SSMS无法连接,优先解决数据库端配置问题。
  • 在代码中添加连接测试:
    // Program.cs中添加测试代码
    using (var db = new DBContext(builder.Configuration))
    {
        try
        {
            bool canConnect = db.Database.CanConnect();
            Console.WriteLine(canConnect ? "数据库连接成功" : "数据库连接失败");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"连接错误:{ex.Message}");
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:05:14