如何在ASP.NET Core 6 MVC中实现ASP.NET 4.x的AnonymousId功能
在ASP.NET Core 6 MVC中实现AnonymousId功能的方案
一、替代老旧NuGet包的自研实现思路
与其纠结现有包的依赖冗余问题,不如直接基于ASP.NET Core的身份体系自定义实现匿名ID功能,步骤如下:
- 编写自定义中间件
AnonymousIdMiddleware,在请求管道中处理匿名用户标识:public class AnonymousIdMiddleware { private readonly RequestDelegate _next; private const string AnonymousCookieKey = ".ASPXANONYMOUS"; public AnonymousIdMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { if (!context.User.Identity.IsAuthenticated) { var anonymousId = context.Request.Cookies[AnonymousCookieKey]; if (string.IsNullOrWhiteSpace(anonymousId)) { anonymousId = Guid.NewGuid().ToString("N"); var cookieOpts = new CookieOptions { HttpOnly = true, Secure = context.Request.IsHttps, SameSite = SameSiteMode.Lax, Expires = DateTimeOffset.UtcNow.AddYears(1) }; context.Response.Cookies.Append(AnonymousCookieKey, anonymousId, cookieOpts); } // 为匿名用户添加标识声明 var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, anonymousId) }, "Anonymous"); context.User.AddIdentity(identity); } await _next(context); } } - 在
Program.cs中注册中间件(需放在身份认证中间件之后):app.UseAuthentication(); app.UseAuthorization(); // 注册自定义匿名ID中间件 app.UseMiddleware<AnonymousIdMiddleware>(); - 在业务代码中获取匿名ID:
var anonymousId = User.FindFirstValue(ClaimTypes.NameIdentifier);
二、关于KJensen更新NuGet包的推测
如果一定要沿用那个提及的NuGet包,他的更新逻辑大概率是:
- 移除对.NET Framework旧版本的依赖,替换为ASP.NET Core 3.1的原生API;
- 重构包内的中间件逻辑,适配ASP.NET Core的请求管道模型;
- 清理冗余依赖项,仅保留
Microsoft.AspNetCore.Http、Microsoft.AspNetCore.Authentication等必要的ASP.NET Core组件; - 重新编译打包,发布适配.NET Core 3.1的版本。
三、方案选择建议
- 自研方案更轻量,无额外依赖,完全适配ASP.NET Core 6,后续维护和扩展更可控;
- 若坚持使用现有NuGet包,建议查看包的开源源码(如有),手动剔除不必要的依赖,或基于源码重新编译适配ASP.NET Core 6的版本。
内容的提问来源于stack exchange,提问作者Shiloh
相关产品推荐
相关产品推荐

