什么是从服务层发送和返回数据对象的更好设计

时间:2014-09-04 02:29:04

标签: asp.net asp.net-mvc-4 asp.net-mvc-5

我可能想的太多了,但是想知道是否有更有效的方法来做到以下几点。请注意,我主要关心的是使用数据传输对象。这对我来说非常好看。

示例DTO:

 public class UserDto:DtoBase
{
    public Guid UserId { get; set; }
    public Guid NamedIdentifier { get; set; }
    public string ProviderIdentifier { get; set; }
    public string ProviderName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Salt { get; set; }
    public DateTime PasswordExpirationDate { get; set; }
    public int InvalidLoginAttempts { get; set; }
    public int AccountLocked { get; set; }
    public int AccountValidated { get; set; }
    public string AccountKey { get; set; }
    public IList<string> Roles { get; set; }
    public DateTime LastLoginDate { get; set; }
    public ProfileDto Profile { get; set; }
}

示例服务方法。

  public CreateUserResult CreateUser(UserDto userDto)
    {
        ISession session = _sessionManager.OpenSession();
        int accountValidated = 1;

        try
        {
            if (_applicationConfiguration.AccountValidationEnabled)
            {
                accountValidated = 0;
            }

            if (session.QueryOver<User>().Where(x => x.UserName == userDto.UserName).RowCount() > 0)
            {
                return new CreateUserResult
                {
                    CreateUserStatus = CreateUserStatus.UserExists
                };
            }

            string accountKey = _encryption.GenerateMd5HashString(_encryption.GenerateRandomString(8));
            string hash;
            string salt;

            _encryption.GethashAndSaltString(userDto.Password, out hash, out salt);

            IList<Role> roles =
                session.QueryOver<Role>().Cacheable().CacheMode(CacheMode.Normal).Take(10).List<Role>();

            var userEntity = new User
            {
                UserName = userDto.UserName,
                Password = hash,
                Salt = salt,
                PasswordExpires = _applicationConfiguration.PasswordExpirationDays,
                InvalidLoginAttempts = 0,
                AccountLocked = 0,
                AccountValidated = accountValidated,
                AccountKey = accountKey,
                Active = 1,
                LastLoginDate = DateTime.UtcNow,
                DateCreated = DateTime.UtcNow,
                LastUpdated = DateTime.UtcNow,
                Profile = new Profile
                {
                    DisplayName = userDto.Profile.DisplayName,
                    EmailAddress = userDto.Profile.EmailAddress,
                    Bio = userDto.Profile.Bio,
                    Active = 1,
                    DateCreated = DateTime.UtcNow,
                    LastUpdated = DateTime.UtcNow
                },
            };
            foreach (Role roleEntity in
                userDto.Roles.Where(role => roles.Any(x => x.Name == role))
                    .Select(role => roles.SingleOrDefault(x => x.Name == role))
                    .Where(roleEntity => roleEntity != null))
            {
                userEntity.Roles.Add(roleEntity);
            }

            session.Save(userEntity);

            return new CreateUserResult
            {
                CreateUserStatus = CreateUserStatus.Success,
                User = new UserDto
                {
                    UserId = userEntity.UserId,
                    NamedIdentifier = userEntity.UserId,
                    UserName = userEntity.UserName,
                    Password = userEntity.Password,
                    Salt = userEntity.Salt,
                    PasswordExpirationDate = userEntity.PasswordExpires,
                    InvalidLoginAttempts = userEntity.InvalidLoginAttempts,
                    AccountLocked = userEntity.AccountLocked,
                    AccountValidated = userEntity.AccountValidated,
                    AccountKey = userEntity.AccountKey,
                    Active = userEntity.Active,
                    LastLoginDate = userEntity.LastLoginDate,
                    DateCreated = userEntity.DateCreated,
                    LastUpdated = userEntity.LastLoginDate,
                    Profile = new ProfileDto
                    {
                        ProfileId = userEntity.Profile.ProfileId,
                        DisplayName = userEntity.Profile.DisplayName,
                        EmailAddress = userEntity.Profile.EmailAddress,
                        Bio = userEntity.Profile.Bio,
                        Active = userEntity.Profile.Active,
                        DateCreated = userEntity.Profile.DateCreated,
                        LastUpdated = userEntity.Profile.LastUpdated
                    },
                    Roles = userEntity.Roles.Select(x => x.Name).ToList()
                }
            };
        }
        catch (Exception exception)
        {
            _logger.Error(exception.Message);

            return new CreateUserResult
            {
                CreateUserStatus = CreateUserStatus.Failed
            };
        }
    }

Controller ActionResult:

 [AllowAnonymous]
    [ValidateAntiForgeryToken]
    [HttpPost]
    public ActionResult SignUp(UsersSignUpViewModel usersSignUpViewModel)
    {
        if (!ModelState.IsValid)
        {
            return View(usersSignUpViewModel);
        }
        string userName = usersSignUpViewModel.UserName;
        string password = usersSignUpViewModel.Password;
        string displayName = usersSignUpViewModel.DisplayName;
        string returnUrl = usersSignUpViewModel.ReturnUrl;

        if (!Url.IsLocalUrl(returnUrl) || string.IsNullOrEmpty(returnUrl))
        {
            returnUrl = "/";
        }

        var user = new UserDto
        {
            UserName = userName,
            Password = password,
            Roles = new[] {_applicationConfiguration.DefaultRole, "Admin"},
            Profile = new ProfileDto
            {
                DisplayName = displayName,
                EmailAddress = userName
            }
        };
        CreateUserResult createUserResult = _userService.CreateUser(user);

        switch (createUserResult.CreateUserStatus)
        {
            case CreateUserStatus.Success:
                UserDto userResult = createUserResult.User;
                ClaimsIdentity identity = _identityManager.GetIdentity(createUserResult.User);
                _owinContext.Authentication.SignIn(new AuthenticationProperties
                {
                    IsPersistent = false
                }, identity);

                return Json(new {authenticated=true,returnUrl=returnUrl});

            case CreateUserStatus.Failed:
                break;
            case CreateUserStatus.UserExists:
                ModelState.AddModelError("UserName", "Unable to create account");
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }

        return PartialView("_SignUp", usersSignUpViewModel);
    }

1 个答案:

答案 0 :(得分:0)

当然,您应该只返回所需的属性。如果你结束了几个只有几个属性不同的对象,那就没关系。但是不要在DTO中包含在特定情况下未使用的属性。