我正在玩一些代碼,並且需要關於一些項目的意見。 我需要從認證服務返回一個用戶對象回我的控制器,通過Ninject注入控制器。所以每個人都在同一頁面上。這裏是控制器代碼以及一些服務代碼。MVC 3/C#總體設計意見
在登錄ActionResult中,我檢查用戶是否存在,如果他們這樣做,我將使用身份驗證服務對他們進行身份驗證。好吧,很簡單,它返回true | false。我還希望用戶可以做更多的事情,我已經打到數據庫,爲什麼回去再打一次。正如你在驗證服務中看到的,我已經設置了一個很好的用戶對象。
現在最大的問題!!!我應該返回用戶還是IUser?我的想法....我不希望我的控制器取決於具體的用戶,所以我想通過ninject和ctor Inject Iuser將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;
}
}
您的用戶類型沒有任何邏輯(我的意思是,它沒有方法)所以,爲什麼要使用接口IUser隔離它?這是所有類型的用戶都應簽署的合同? 我認爲你的服務必須檢索用戶類型,而不是IUser類型。 – lontivero
AuthenticationService從存儲庫創建/檢索用戶。我只需要將User對象返回給控制器。 – CrazyCoderz
簡單地返回IQueryable是可以接受的/可能的 – CrazyCoderz