[英]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.