简体   繁体   中英

C# Get property values from an Object

Throughout my WebApp project, i'm logging the details of the current user across most of the controller/razor page model methods. I moved the code used for retrieving the current user into a repository and return an object to the calling method.

I'm not sure how to get the values of the properties returned in the object.

Class:

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;
    }
}

Controller Method:

object currentUser = _currentUser.GetCurrentUser();

在此处输入图像描述

I'm looking to use the least amount of code possible to get the values of these properties returned given I'll be using this for most methods throughout the application, thanks

As per comments from 'Rufus' the code below did the trick, thanks

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM