IHttpContextAccessor 范围
我将 IHttpContextAccessor 注入到控制器中。我正在从 IHttpContextAccessor 读取用户名并将其返回给 UI。
我的问题是非常基本的。我需要了解当多个用户连接并请求用户名时这将如何工作。
我只是想确保仅返回相应用户的用户名。
我不想在返回客户端后将用户名保存在会话变量中。每当需要时,我都会请求调用并从上下文中获取它。
这种方法有效吗?
private IHttpContextAccessor ctx
public EmployeeController(IHttpContextAccessor context)
{
ctx=context;
}
public string GetEmployeeName()
{
return ctx.HttpContext.User.UserName;
}
I have IHttpContextAccessor injected in a controller. I am reading user name from IHttpContextAccessor and returning it back to the UI.
My question is is very basic. I need to understand how this will work when multiple users will connect and request User Name.
I just want to make sure that the user names will be returned only for the corresponding user.
I don't want to save the user name in session variable after returned to the client. Whenever is needed, I will request a call and get it from the context.
Is this approach valid?
private IHttpContextAccessor ctx
public EmployeeController(IHttpContextAccessor context)
{
ctx=context;
}
public string GetEmployeeName()
{
return ctx.HttpContext.User.UserName;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用 HttpContextAccessor 时,HttpContextAccessor 将被注册为单例服务
称为 AddHttpContextAccessor。
根据源代码,你会发现 HttpContextAccessor 会检查 _httpContextCurrent 值它调用 get 和 set 方法。当新请求到达应用程序时,它将自动设置 _httpContextCurrent.Value。
The HttpContextAccessor will be registered as the Singleton service when you
called AddHttpContextAccessor.
According to the source codes, you could find the HttpContextAccessor will check the _httpContextCurrent value when it call get and set method. It will auto set the _httpContextCurrent.Value when the new request come to the application.