Asp.net core 向asp.net core 2中的ClaimsPrincipal用户添加自定义属性
根据标题上的描述,我创建了一个类,该类派生自Asp.net core 向asp.net core 2中的ClaimsPrincipal用户添加自定义属性,asp.net-core,asp.net-core-2.0,asp.net-core-webapi,Asp.net Core,Asp.net Core 2.0,Asp.net Core Webapi,根据标题上的描述,我创建了一个类,该类派生自ClaimsPrincipal,并具有其他属性: public class CustomeUser: ClaimsPrincipal { // additional properties } 编写了一个中间件,并从声明中为其赋值: public async Task Invoke(HttpContext context) { // context to read header and assign to custome propertie
ClaimsPrincipal
,并具有其他属性:
public class CustomeUser: ClaimsPrincipal
{
// additional properties
}
编写了一个中间件,并从声明中为其赋值:
public async Task Invoke(HttpContext context)
{
// context to read header and assign to custome properties
context.User = new CustomeUser() {
ClientIP = /*reading from claims*/,
UserId = /*reading from claims*/};
}
在配置服务中,添加以下行以获取HttpContext
,从启动类中的控制器获取该自定义用户属性
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
这是正确的方法吗?如果从控制器访问
HttpContext
,则不需要IHttpContextAccessor
Microsoft.AspNetCore.Mvc.ControllerBase
类,控制器从该类继承(通过控制器类)具有HttpContext
属性。因此,您的代码可以更改为:
public BaseController()
{
customeUser = HttpContext.User as CustomeUser;
}
其余的似乎都很好
HttpContext.User
将包含您填写的Invoke()
方法的CustomeUser
实例,这样到CustomeUser
的恶劣类型转换就可以正常工作。如果您从控制器访问HttpContext
,则不需要IHttpContextAccessor
Microsoft.AspNetCore.Mvc.ControllerBase
类,控制器从该类继承(通过控制器类)具有HttpContext
属性。因此,您的代码可以更改为:
public BaseController()
{
customeUser = HttpContext.User as CustomeUser;
}
其余的似乎都很好
HttpContext.User
将包含您填写的CustomeUser
的实例Invoke()
方法,以便将讨厌的类型转换为CustomeUser
会很好地工作。非常感谢您的建议,但在我运行项目后不久,我得到的HttpContext为空。我想我习惯在这里使用IHttpContextAccessor注入。有什么想法吗?codefuller?很抱歉这样不准确。HttpContext将在控制器构造函数中具有null
值,但是如果从控制器操作调用它,则该值将被填充。在BaseController中没有强制转换的情况下,您建议如何执行此操作?如果要使用从ClaimsPrincipal
派生的类并避免类型强制转换,然后您应该有一些CustomUser
类型的字段,其中存储创建的用户实例。选项之一-使用身份验证中间件创建的CustomUser
对象的一些全局字典。但我会远离这样的解决方案。在这种情况下,Cast没有那么邪恶。非常感谢Verymuch的建议,但在我运行该项目后不久,我得到的HttpContext是空的。我想我习惯在这里使用IHttpContextAccessor注入。有没有更完整的代码?很抱歉这样的错误。HttpContext将在控制器构造函数中具有null
值,但是如果从控制器操作调用它,则该值将被填充。在BaseController中没有强制转换的情况下,您建议如何执行此操作?如果要使用从ClaimsPrincipal
派生的类并避免类型强制转换,然后您应该有一些CustomUser
类型的字段,其中存储创建的用户实例。选项之一-使用身份验证中间件创建的CustomUser
对象的一些全局字典。但我会远离这样的解决方案。在这种情况下,演员阵容就没有那么邪恶了。