Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.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
C#从对象获取属性值_C#_Object_Properties_.net Core 3.1 - Fatal编程技术网

C#从对象获取属性值

C#从对象获取属性值,c#,object,properties,.net-core-3.1,C#,Object,Properties,.net Core 3.1,在我的WebApp项目中,我通过大多数controller/razor页面模型方法记录当前用户的详细信息。我将用于检索当前用户的代码移动到存储库中,并将对象返回给调用方法 我不知道如何获取对象中返回的属性值 类别: public class CurrentUser : ICurrentUser { private readonly IHttpContextAccessor _httpContextAccessor; public CurrentUser(IHttpContext

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

我不知道如何获取对象中返回的属性值

类别:

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();


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

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

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

为什么要返回type
object
而不是type
CurrentUserProperties
?您可能应该从
GetCurrentUser
返回
CurrentUserProperties
类型。否则,可以将返回值强制转换为正确的类型:
CurrentUserProperties currentUser=(CurrentUserProperties)\u currentUser.GetCurrentUser()