【发布时间】:2014-08-22 21:12:24
【问题描述】:
我是 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);
}
【问题讨论】:
-
在数据库中找不到 emailAddress 或密码时触发
-
不,它没有。您应该使用
SingleOrDefault()而不是Single(),然后如果数据不在数据库中,您将获得null。无论如何,天哪,我希望您不要在生产环境中进行这样的身份验证!使用 ASP.NET Identity (2.0) 有什么问题?它为您处理所有棘手的部分,并且也使用 EntityFramework 工作,因此在您的情况下很容易使用。 -
谢谢 Luann 我会考虑你提到的身份验证。任何链接作为起点
标签: c# entity-framework asp.net-mvc-4 asp.net-web-api