[英]How to handle System.InvalidOperationException in entity framework?
我是ASP.NET Web API的新手。 我做了一個應該驗證用戶前端發送數據的功能,然后我在數據庫中搜索數據。 但是,當找不到該帳戶時,我總是會遇到一個異常,該如何處理該異常以將其發送到前端信息?當第一個if語句不正確時,我應該返回什么,因為null無效。
public UserData ByPassword(string emailAddress, string password)
{
if (emailAddress != null && password != null)
{
Account account = db.Accounts.Where(acc => acc.AccMail == emailAddress && acc.AccPassword == password.ToLower()).Single();
string token = OurAuthorizationAttribute.CreateTicket(account.AccID, false);
UserData data = new UserData();
data.Id = account.AccID;
data.Token = token;
return data;
}
她也我有添加嘗試和捕獲塊,但仍然是同樣的問題。
public UserData ByPassword(string emailAddress, string password)
{
if (emailAddress != null && password != null)
{
try
{
Account account = db.Accounts.Where(acc => acc.AccMail == emailAddress && acc.AccPassword == password.ToLower()).Single();
string token = OurAuthorizationAttribute.CreateTicket(account.AccID, false);
UserData data = new UserData();
data.Id = account.AccID;
data.Token = token;
return data;
}
catch
{
throw new OurException(OurExceptionType.InvalidCredentials);
}
}
throw new OurException(OurExceptionType.InvalidCredentials);
}
System.InvalidOperationException
指示編程錯誤。 您可以通過修復代碼來處理它。
在這種特殊情況下,此行中的錯誤是:
Account account = db.Accounts.Where(acc => acc.AccMail == emailAddress && acc.AccPassword == password.ToLower()).Single();
您的代碼假設“ Accounts
必須包含任何{emailAddress, password}
對的記錄,這是不正確的。 用SingleOrDefault
替換Single
將使異常消失。 當然,您需要對結果進行空檢查以查看記錄是否存在。
這是更改代碼的方法:
public UserData ByPassword(string emailAddress, string password) {
// null-check your arguments to detect programming errors in the "upstream" code
if (emailAddress == null) throw new ArgumentNullException("emailAddress");
if (password == null) throw new ArgumentNullException("password");
// Now that your arguments are "sanitized", fix the Single() call
Account account = db.Accounts.Where(acc => acc.AccMail == emailAddress && acc.AccPassword == password.ToLower()).SingleOrDefault();
// Missing credentials is not a programming error - throw your specific exception here:
if (account == null) {
throw new OurException(OurExceptionType.InvalidCredentials);
}
string token = OurAuthorizationAttribute.CreateTicket(account.AccID, false);
UserData data = new UserData();
data.Id = account.AccID;
data.Token = token;
return data;
}
注意:盡管以上更改將解決編碼錯誤,但不會解決將密碼存儲為純文本的主要設計缺陷。 有關在數據庫中存儲密碼的深入討論,請參閱此問題 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.