use*_*801 3 autofac asp.net-core
我使用 autofac PropertiesAutowired 方法(ASP.NET CORE)。我需要的是获取类库项目中的当前用户。我该怎么做?我想要这样的东西
public IHttpContextAccessor ContextAccessor{ get; set; }
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它
Context.HttpContext.User.Claims.First(i => i.Type == "NameIdentifier"
Run Code Online (Sandbox Code Playgroud)
是否可以这样做或者我应该使用其他东西来实现它?
注意:以下仅在按照此处或此处所述向 ASP.NET Core 注册 Autofac 时有效。
如果不需要对属性使用自动装配,我建议您执行以下操作
首先,将依赖项注册为单例(是的,这不是问题,MS也是这样做的)
builder.RegisterType<HttpContextAccessor>()
.As<IHttpContextAccessor>()
.SingleInstance();
Run Code Online (Sandbox Code Playgroud)
假设你的类被称为MyClass通过构造函数注入它
public MyClass(IHttpContextAccessor httpContextAccessor)
{
ContextAccessor = httpContextAccessor;
}
Run Code Online (Sandbox Code Playgroud)
现在你可以走了!我确信您可以使其与属性自动装配一起使用,但我不熟悉这种方法。
作为旁注:
如果您想检索经过身份验证的用户的信息,我听说并读到建议编写类似ApplicationUser包装底层框架逻辑的类之类的内容。
我在这里实现了类似的东西,它也用于IHttpContextAccessor检索所需的声明+我也在使用 autofac 注册访问器。唯一的区别是我使用构造函数注入。
我希望这对你有帮助!
| 归档时间: |
|
| 查看次数: |
3242 次 |
| 最近记录: |