C# 从对象中获取属性值

OJB1

在我的 WebApp 项目中,我记录了大多数控制器/剃刀页面模型方法中当前用户的详细信息。我将用于检索当前用户的代码移到存储库中,并将对象返回给调用方法。

我不确定如何获取对象中返回的属性的值。

班级:

public class CurrentUser : ICurrentUser
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CurrentUser(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public class CurrentUserProperties
    {
        public string Id { get; set; }
        public string Username { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
    }

    public object GetCurrentUser()
    {
        CurrentUserProperties currentUser = new CurrentUserProperties
        {
            Id = _httpContextAccessor.HttpContext.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value,
            Username = _httpContextAccessor.HttpContext.User.Identity.Name,
            Forename = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value,
            Surname = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value
        };
        return currentUser;
    }
}

控制器方法:

object currentUser = _currentUser.GetCurrentUser();

在此处输入图片说明

我希望使用尽可能少的代码来获取返回的这些属性的值,因为我将在整个应用程序的大多数方法中使用它,谢谢

OJB1

根据'Rufus'的评论,下面的代码可以解决问题,谢谢

CurrentUserProperties currentUser = (CurrentUserProperties)_currentUser.GetCurrentUser();

        var userId = currentUser.Id;
        var username = currentUser.Username;
        var forename = currentUser.Forename;
        var surname = currentUser.Surname;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C#在BackgroundWorker中BeginInvoke,获取对象属性值

在 C# 中获取属性的值

获取C#中属性的值

在 C# 中获取属性的值

查找对象的属性并获取其值-C#

C#-从ComboBox对象属性获取int值

C# - 获取列表中的 3 个最低值,由列表中对象的公共属性衡量

如何在 C# 中获取类属性的属性值

从C#中的JSON对象获取对象值

从C#中的动态对象中删除属性及其值

从C#中的“托管对象”属性获取值的最佳方法

如何从C#中的对象数组中获取不同的值?

使用C#反射,如果该对象是列表内的对象的属性,则如何获取对象的属性及其值

从C#中的参数属性访问对象值

根据C#中的对象列表中不同属性的值组合某个属性的值?

如何在C#中使用对象ID属性获取对象值

是否有可能通过c#中的值获取属性

获取 href 属性值时 HTMLAgilityPack 中的错误。C#

在C#中获取属性值(反射)的最快方法

c#从类的实例中获取静态属性的值

获取变量的值并在C#中作为属性赋值

如何在C#中通过反射获取属性值

获取C#中的单个属性值的列表-反射

在 Linq C# 中获取链接的对象值

在C#中获取对象数组的键和值

如何在C#中获取另一个对象的属性的对象类型?

使用CsvHelper时如何从C#动态对象获取属性名称和值?

C#获取C#中某种对象类型的所有属性

在c#中通过属性名动态从类的对象中获取值