如何在entity framework中处理System.InvalidOperationException?

我是asp.net web API的新手。 我已经制作了一个function,应该validation用户前端发​​送数据,然后我搜索数据库中的数据。 但是当找不到帐户时,我总是得到一个例外,我应该如何处理该exception以发送到前端信息,当第一个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; } 

她还添加了try和catch块,但仍然是同样的问题。

 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会使exception消失。 当然,您需要对结果进行空检查以查看记录是否存在。

以下是更改代码的方法:

 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; } 

注意:虽然上述更改将修复编码错误,但它无法解决以纯文本格式存储密码的主要设计缺陷。 有关在数据库中存储密码的深入讨论,请参阅此问题 。