Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core 向asp.net core 2中的ClaimsPrincipal用户添加自定义属性_Asp.net Core_Asp.net Core 2.0_Asp.net Core Webapi - Fatal编程技术网

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
对象的一些全局字典。但我会远离这样的解决方案。在这种情况下,演员阵容就没有那么邪恶了。