如何处理系统.实体框架中的InvalidOperationException
本文关键字:InvalidOperationException 框架 实体 处理系统 | 更新日期: 2023-09-27 18:11:00
我是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;
}
我也添加了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
将使异常消失。当然,您需要对结果进行null检查,以查看记录是否存在。
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;
}
注意:虽然上面的更改会修复编码错误,但它不会解决以明文形式存储密码的主要设计缺陷。有关在数据库中存储密码的深入讨论,请参阅此问题。