将自定义属性添加到asp.net core 2中的ClaimsPrincipal用户

编程入门 行业动态 更新时间:2024-10-19 02:24:46
本文介绍了将自定义属性添加到asp 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用户

本文发布于:2023-11-15 02:51:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1590489.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   属性   用户   ClaimsPrincipal   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!