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

.NET 4.5迁移至.NET Core 6:System.Web.Security与HttpContext替代方案咨询

ASP.NET Core 6 替代 System.Web.Security 与 HttpContext.Current 的方案

核心变化说明

ASP.NET Core 彻底移除了System.Web相关组件,包括RoleProvider和HttpContext.Current,需要改用依赖注入和现代化的认证授权体系实现原有功能。

方案一:自定义用户信息服务(替代原CustomRoleProvider)

1. 注册必要服务

在Program.cs中添加IHttpContextAccessor和自定义服务的注册:

// 注册HttpContext访问器
builder.Services.AddHttpContextAccessor();
// 注册自定义用户服务
builder.Services.AddScoped<CustomUserService>();
// 注册数据库上下文(根据你的连接字符串配置调整)
builder.Services.AddDbContext<PIBQWS_prodContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("YourConnectionString")));

2. 重构用户信息服务

不再继承RoleProvider,改为通过依赖注入获取HttpContext和数据库上下文:

using System;
using System.Linq;
using Ibq.Wages.ManagementSystem.Models;
using Microsoft.AspNetCore.Http;

namespace Ibq.Wages.ManagementSystem.Services
{
    public class CustomUserService
    {
        public int UserCompanyId { get; private set; }
        public string PayerQid { get; private set; }
        public string PayerEid { get; private set; }
        public bool OTPCompleted { get; private set; }
        public int? AuthorizationLevels { get; private set; } 

        private readonly PIBQWS_prodContext _dbContext;
        private readonly IHttpContextAccessor _httpContextAccessor;

        // 通过构造函数注入依赖
        public CustomUserService(PIBQWS_prodContext dbContext, IHttpContextAccessor httpContextAccessor)
        {
            _dbContext = dbContext;
            _httpContextAccessor = httpContextAccessor;
        }

        // 加载用户信息的方法,在需要时调用(如控制器Action、中间件)
        public void LoadUserInfo()
        {
            var userName = _httpContextAccessor.HttpContext?.User?.Identity?.Name;
            if (!string.IsNullOrEmpty(userName))
            {
                // 替换为你原有的UserCompany方法逻辑
                var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
                if (user != null)
                {
                    UserCompanyId = user.CompanyId;
                    PayerQid = user.PayerQid;
                    PayerEid = user.PayerEid;
                    OTPCompleted = user.OTPCompleted;
                    AuthorizationLevels = user.AuthorizationLevels;
                }
            }
        }
    }
}

3. 使用方式

在控制器中注入服务并调用:

public class HomeController : Controller
{
    private readonly CustomUserService _userService;

    public HomeController(CustomUserService userService)
    {
        _userService = userService;
    }

    public IActionResult Index()
    {
        _userService.LoadUserInfo();
        // 使用_userService中的属性
        ViewBag.CompanyId = _userService.UserCompanyId;
        return View();
    }
}

方案二:通过ClaimsTransformation嵌入用户信息(推荐)

将用户信息添加到认证Claims中,整个请求生命周期内可直接通过HttpContext.User访问:

1. 实现IClaimsTransformation

using System.Security.Claims;
using System.Threading.Tasks;
using System.Linq;
using Ibq.Wages.ManagementSystem.Models;
using Microsoft.AspNetCore.Authentication;

namespace Ibq.Wages.ManagementSystem.Services
{
    public class CustomClaimsTransformer : IClaimsTransformation
    {
        private readonly PIBQWS_prodContext _dbContext;

        public CustomClaimsTransformer(PIBQWS_prodContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var userName = principal.Identity?.Name;
            if (!string.IsNullOrEmpty(userName) && principal.Identity is ClaimsIdentity identity)
            {
                // 查询用户信息
                var user = _dbContext.Users.FirstOrDefault(u => u.UserName == userName);
                if (user != null)
                {
                    // 添加自定义Claims
                    identity.AddClaim(new Claim("CompanyId", user.CompanyId.ToString()));
                    identity.AddClaim(new Claim("PayerQid", user.PayerQid));
                    identity.AddClaim(new Claim("PayerEid", user.PayerEid));
                    identity.AddClaim(new Claim("OTPCompleted", user.OTPCompleted.ToString()));
                    
                    if (user.AuthorizationLevels.HasValue)
                    {
                        identity.AddClaim(new Claim("AuthorizationLevels", user.AuthorizationLevels.Value.ToString()));
                    }

                    // 添加角色Claims(用于角色授权)
                    foreach (var role in user.Roles)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, role.Name));
                    }
                }
            }
            return principal;
        }
    }
}

2. 注册服务

在Program.cs中添加:

builder.Services.AddTransient<IClaimsTransformation, CustomClaimsTransformer>();

3. 使用方式

在任意需要的地方直接从HttpContext获取:

public IActionResult Index()
{
    var companyId = int.Parse(User.FindFirst("CompanyId")?.Value ?? "0");
    var payerQid = User.FindFirst("PayerQid")?.Value;
    // 其他信息同理
    return View();
}

关键注意事项

  • 禁止在服务构造函数中直接访问HttpContext:因为服务初始化时HttpContext可能尚未创建,需通过IHttpContextAccessor延迟获取。
  • 原RoleProvider的角色授权功能,在ASP.NET Core中通过[Authorize(Roles = "Admin")]特性结合Claims中的ClaimTypes.Role实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:40:51