我正在使用简单的会员提供商构建MVC 4 Web应用程序,我有管理,我可以编辑用户的用户名和密码。当我只编辑用户名或密码时,它是可以的,但是当我尝试编辑用户名和密码时同时当我尝试使用新用户名登录时,用户列表中显示的UserProfiles用户名是旧用户名,尽管数据库中的记录已更改。这是一个代码示例:
[HttpPost]
public ActionResult EditUser(RegisterUserModel model, FormCollection form)
{
if (ModelState.IsValid)
{
var oldUserName = form["userHidden"];
var newUserName = model.UserName;
bool isOldPassword = Membership.ValidateUser(oldUserName , model.Password);
if (!isOldPassword)
{
var token = WebSecurity.GeneratePasswordResetToken(oldUserName );
try
{
//Reset password using the reset token and the new password
WebSecurity.ResetPassword(token, model.Password);
}
catch (Exception e)
{
ModelState.AddModelError("", String.Format("{0} Exception caught.", e));
}
}
if (newUserName != null && oldUserName != null)
{
if (newUserName.ToLower() != oldUserName.ToLower())
{
myRepository.ChangeUserName(oldUserName, newUserName);
myRepository.Save();
}
}
return RedirectToAction("Users", "Administration");
}
ModelState.AddModelError("", "Please enter correct username and password.");
return View(model);
}
这是我的ChangeUserName方法:
public void ChangeUserName(string oldUserName, string newUserName)
{
var userToUpdate = (from user
in context.Users
where user.Username == oldUserName
select user).FirstOrDefault();
if (userToUpdate != null)
{
var updatedUser = new Users();
updatedUser.UserId = userToUpdate.UserId;
updatedUser.UserName = newUserName;
context.Entry(userToUpdate).CurrentValues.SetValues(updatedUser);
}
}
我已经扩展了我的会员资格:
public class ExtendMembership
{
private static IMyRepository myRepository= new MyRepository(new MyEntities());
public static bool ValidateUser(string username, string password, string companyName)
{
int companyId = myRepository.GetCompanyName(companyName);
int? userId = companyId == 0 ? null : GetUserId(username, companyId);
if (userId.HasValue && userId.Value != 0)
{
var userKeyToCompany = username + "@" + companyName.ToLower();
return WebSecurity.Login(userKeyToCompany , password);
}
else
{
return false;
}
}
private static int? GetUserId(string username, int companyId)
{
var userId = (from users
in myRepository.GetUsers()
where (users.UserName.ToLower() == username.ToLower()) && (users.CompanyId == companyId)
select users.UserId).FirstOrDefault();
return userId;
}
}
GetUserId方法获取公司用户的ID
答案 0 :(得分:1)
您应该考虑使用构造而不是静态存储库。如果处理大量请求,静态存储库将会重新启动。以下是您可以使用的使用示例:
using(var myRepository = new MyRepository(new MyEntities())) {
... code here
}
答案 1 :(得分:0)
事实证明,我的GetUserId方法应该在更改的上下文中实现的MyRepository中,并且还应该更改密码和更改用户名操作。这解决了一切。