ASP.NET Core 中的一种实现方法
1、实现一个 Action Filter
public class SampleActionFilter : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "test") }, "Basic"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); context.HttpContext.User = claimsPrincipal; await next(); } }
2、在 Startup.cs 中注册这个 Filter
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add<SampleActionFilter>(); }); }
3、在 Action 中读取 Action Fitler 中设置的用户信息
public class HomeController : Controller { public IActionResult Index() { return Content("Current User: " + User.Identity.Name ); } }
4、运行结果
Current User: test
学习了,非常感谢您
线程静态也是可以的.
最好还是放在请求上下文中