對不起,我會盡我所能去做。SaveChanges()在拋出異常之前不起作用
我有實體「Usuario」從rbacManager接收對象,調用Login方法(見下文)。如您所見,此方法在無法與用戶密碼匹配時引發異常。在這種情況下,我必須增加屬性Intentos,以允許用戶只有三次失敗的機會。
問題如下:SaveChanges方法未保存在Usuario中修改的值。我認爲SaveChanges方法由於例外而失敗,但我不確定。我在網上找不到任何幫助。
這是操作方法登錄:
using(EntitiesModel dbContext = new EntitiesModel())
{
try
{
string hPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "SHA1");
Usuario usuario = this.rbacManager.Login(model.UserName, hPassword);
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
return RedirectToAction("Index", "Home");
}
catch (LoginIncorrectoException)
{
dbContext.SaveChanges();
ViewData["Message"] = "User incorrect.";
}
catch (UsuarioBloqueadoException)
{
ViewData["Message"] = "User locked";
}
return View(model);
}
而第四行的方法登錄,拋出異常:
using (EntitiesModel context = new EntitiesModel())
{
Usuario usuario = this.GetUsuario(username);
if (usuario == null)
throw new LoginIncorrectoException();
if (!usuario.EstaActivo())
{
throw new UsuarioBloqueadoException();
}
if (usuario.Password != password)
{
usuario.Intentos++;
if (usuario.Intentos >= 3)
{
usuario.Activo = false;
context.SaveChanges();
throw new UsuarioBloqueadoException();
}
else
{
context.SaveChanges();
throw new LoginIncorrectoException();
}
}
usuario.Intentos = 0;
return usuario;
}
編輯:我複製GetUsuario方法。
private Usuario GetUsuario(string username)
{
using (EntitiesModel context = new EntitiesModel())
{
List<Usuario> Usuarios = context
.Usuarios
.Where(x => x.Username == username)
.ToList();
if (Usuarios.Count == 1)
return Usuarios.First();
else
throw null;
}
}
任何人都知道爲什麼SaveChanges不起作用? 謝謝!
如你所見,異常是從方法中退出,我在logOn中捕獲它。當我在三次失敗日誌之後鎖定用戶時,SaveChanges未保存在Usuario對象中修改的值,例如「usuario.Intentos ++」,當我必須增加記錄機會的計數器或「usuario.Activo = false」時。我在Login方法中這樣做。 – 2013-02-14 13:53:19
你可以顯示GetUsuario方法的正文嗎? – 2013-02-14 14:00:44