Я играю с некоторым кодом и мне нужно мнение по нескольким пунктам.Мне нужно вернуть объект User обратно на мой контроллер из службы аутентификации, которая вводится в контроллер через Ninject.Так что все на одной странице.Вот код контроллера и некоторые служебные коды.
В Login ActionResult для входа в систему я проверяю, существует ли пользователь, и, если он существует, я проверю его подлинность с помощью службы аутентификации.Хорошо, достаточно просто, он возвращает true | false.Я также хочу кое-что еще с пользователем, я уже попал в базу данных, зачем возвращаться и снова ее.Как вы можете видеть в сервисе аутентификации, я настроил хороший пользовательский объект.
Большой вопрос сейчас !!!Должен ли я вернуть пользователя или пользователя.Мои мысли .... я не хочу, чтобы мой контроллер зависел от конкретного пользователя, поэтому я думал соединить IUser с пользователем через ninject и ctor Inject Iuser.Тогда я мог бы установить _user = _authenticationService.AuthenticateUser (userName, password);
Хорошо, плохо, некрасиво ???мысли ???
Код контроллера:
public class UsersController : Controller
{
private readonly IUserService _userService;
private readonly IAuthenticationService _authenticationService;
public UsersController(IUserService userService,IAuthenticationService authenticationService)
{
_userService = userService;
_authenticationService = authenticationService;
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(UserLoginViewModel userLoginViewModel)
{
string userName = userLoginViewModel.UserName;
string password = userLoginViewModel.Password;
if (_userService.UserExists(userName))
{
//This will change
if (_authenticationService.AuthenticateUser(userName, password))
{
}
}
return PartialView("_Login");
}
public ActionResult Register()
{
return PartialView("_Register");
}
[HttpPost]
public ActionResult Register(UserRegisterViewModel userRegisterViewModel)
{
ModelState.AddModelError("UserName", "Testing");
return PartialView("_Register");
}
}
Сервисный код:
public class AuthenticationService:IAuthenticationService
{
private readonly IRepository _repository;
private readonly IEncryption _encryption;
public AuthenticationService(IRepository repository,IEncryption encryption)
{
_repository = repository;
_encryption = encryption;
}
// HMM! Ok I need to get the User object back to the controller, so instead of returning bool should I return User or IUser.
public bool AuthenticateUser(string userName, string password)
{
try
{
var user = _repository.Select<Users>().Where(u => u.UserName == userName).Select(u => new User
{
UserId = u.UserID,
UserTypeId = u.UserTypeID,
UserName = u.UserName,
Password = u.Password,
Salt = u.Salt,
ActivationCode = u.ActivationCode,
InvalidLoginAttempts = u.InvalidLoginAttempts,
IsLockedOut = u.IsLockedOut,
LastLoginDate = u.LastLoginDate,
Active = u.Active,
DateCreated = u.DateCreated,
LastUpdated = u.LastUpdated
}).Single();
// Check the users password hash
if(_encryption.VerifyHashString(password,user.Password,user.Salt))
{
return true;
}
}
catch (Exception)
{
return false;
}
// get the user from the database
return false;
}
}