HttpContext.User.Identity.IsAuthenticated 为false
您可以通过手动设置HttpContext.User来实现此目的:
var identity = new ClaimsIdentity("Custom");
HttpContext.User = new ClaimsPrincipal(identity);
对于更复杂的东西,您可以添加如下声明:
var identity = new ClaimsIdentity(new List<Claim> { new Claim("UserId", "123", ClaimValueTypes.Integer32) }, "Custom"); HttpContext.User = new ClaimsPrincipal(identity);
这将导致:
HttpContext.User.Identity.IsAuthenticated == true; int.Parse(((ClaimsIdentity)HttpContext.User.Identity).ValueFromType("UserId")) == 123;
获取identity信息
/// <summary> /// 当前用户ID /// </summary> public string UserId { get { if (IsAuthenticated && HttpContextAccessor.HttpContext.User.Claims.Any(s => s.Type == ClaimTypes.Name)) { var result = HttpContextAccessor.HttpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Name).Value; return result; } else { return ""; } } } public IEnumerable<string> RoleKeys { get { if (!string.IsNullOrEmpty(UserId)) { return HttpContextAccessor.HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.Role)?.Select(c => c.Value)?.ToList(); } else { return new List<string>(); } } } public IEnumerable<string> RoleIds { get { var result=new List<string>(); if (!string.IsNullOrEmpty(UserId)) { var roleIds = HttpContextAccessor.HttpContext.User.Claims.SingleOrDefault(c => c.Type == "RoleIds")?.Value; if (!string.IsNullOrEmpty(roleIds)) { result= roleIds.Split(',').ToList(); } } return result; } }
https://cloud.tencent.com/developer/ask/sof/290519
此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2019-04-18 C# C/S程序出错:ContextSwitchDeadlock is detected
2016-04-18 301重定向