将自定义属性添加到asp.net core 2中的ClaimsPrincipal用户 [英] Add Custom properties to ClaimsPrincipal user in asp.net core 2

查看:67
本文介绍了将自定义属性添加到asp.net core 2中的ClaimsPrincipal用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标题说明,我创建了一个类,该类派生自 ClaimsPrincipal ,并具有其他属性:

As per description on title, I have created a class which derived from ClaimsPrincipal and have additional properties:

public class CustomeUser: ClaimsPrincipal
{
   // additional properties
}

编写了一个中间件并为声明中的值分配了值:

Wrote a middleware and assigned values to that from the claims:

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 ,以从启动类中的控制器获取该自定义用户属性.

and in configuration service add following line to get HttpContext to fetch that custom user properties from controller in start up class.

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

从控制器中获取自定义用户属性

from controller to fetch custome user properties

public BaseController(IHttpContextAccessor httpContextAccessor)
{
   customeUser = httpContextAccessor.HttpContext.User as CustomeUser;
}

这是正确的方法吗?

推荐答案

如果从控制器访问 HttpContext ,则不需要 IHttpContextAccessor .控制器从中继承(通过Controller类)的 Microsoft.AspNetCore.Mvc.ControllerBase 类具有 HttpContext 属性.因此,您的代码可以更改为:

You don't need IHttpContextAccessor if you access HttpContext from a controller. Microsoft.AspNetCore.Mvc.ControllerBase class from which controllers inherit (through Controller class) has HttpContext property. So your code could be changed as:

public BaseController()
{
   customeUser = HttpContext.User as CustomeUser;
}

其余的一切似乎都不错. HttpContext.User 将包含您在 Invoke()方法中填写的 CustomeUser 实例,以便将讨厌的类型转换为 CustomeUser 就可以了.

All the rest seems good. HttpContext.User will contain instance of CustomeUser that you filled in Invoke() method so that nasty type conversion to CustomeUser will work just fine.

这篇关于将自定义属性添加到asp.net core 2中的ClaimsPrincipal用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆