我是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);
}
答案 0 :(得分:2)
System.InvalidOperationException
表示编程错误。您可以通过修复代码来处理它。
在这种特殊情况下,错误出现在这一行:
Account account = db.Accounts.Where(acc => acc.AccMail == emailAddress && acc.AccPassword == password.ToLower()).Single();
您的代码假设Accounts
必须包含任何{emailAddress, password}
对的记录,这是不正确的。用Single
替换SingleOrDefault
会使例外消失。当然,您需要对结果进行空检查以查看记录是否存在。
以下是更改代码的方法:
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;
}
注意:虽然上述更改可以解决编码错误,但它无法解决以纯文本格式存储密码的主要设计缺陷。有关在数据库中存储密码的深入讨论,请参阅this question。