【问题标题】:C# Get property values from an ObjectC# 从对象中获取属性值
【发布时间】:2020-07-20 21:15:50
【问题描述】:

在我的 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();

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

【问题讨论】:

  • 你为什么返回object而不是CurrentUserProperties
  • 您可能应该从GetCurrentUser 返回一个CurrentUserProperties 类型。否则,您可以将返回值转换为正确的类型:CurrentUserProperties currentUser = (CurrentUserProperties) _currentUser.GetCurrentUser();

标签: c# object properties .net-core-3.1


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多