我收到错误并非所有代码路径都返回值?
public string Authentication(string studentID, string password) // this line?
{
var result = students.FirstOrDefault(n => n.StudentID == studentID);
//find the StudentID that matches the string studentID
if (result != null)
//if result matches then do this
{
//----------------------------------------------------------------------------
byte[] passwordHash = Hash(password, result.Salt);
string HashedPassword = Convert.ToBase64String(passwordHash);
//----------------------------------------------------------------------------
// take the specific students salt and generate hash/salt for string password (same way student.Passowrd was created)
if (HashedPassword == result.Password)
//check if the HashedPassword (string password) matches the stored student.Password
{
return result.StudentID;
// if it does return the Students ID
}
}
else
//else return a message saying login failed
{
return "Login Failed";
}
}
答案 0 :(得分:6)
如果结果不是null但是result.Password!= HashedPassword你没有返回任何内容。
你应该改为:
...
if (HashedPassword == result.Password)
{
return result.StudentID;
// if it does return the Students ID
}
return "Invalid Password";
...
答案 1 :(得分:4)
问题是由于嵌套的if语句,您的第一个if语句无法确保返回值。想象一下,您将结果设置为值(非空)并且您的散列密码和提供的密码不匹配,如果您遵循该逻辑,则无法返回返回语句。
你应该在你的嵌套if语句中添加一个else子句,如下所示:
if (HashedPassword == result.Password)
//check if the HashedPassword (string password) matches the stored student.Password
{
return result.StudentID;
// if it does return the Students ID
}
else
{
return "Login Failed";
}
或者更理想的是,删除你已经拥有的else语句,以便函数以返回登录失败结束:
if (result != null)
{
//....
}
return "Login Failed";
...使用第二种方法,您无需担心使用else,因为如果满足所有其他条件,嵌套的return语句将终止该函数。如果任何身份验证步骤失败,请尝试将此最终返回视为默认操作
对代码的另一个注意事项是,以这种方式返回混合数据并不是理想的做法。即结果可能是学生ID,也可能是错误消息。考虑创建一个具有多个属性的专用结果类,调用代码可以检查这些属性以查看逻辑验证的状态。类似以下的课程将是一个良好的开端:
public class LoginResult
{
//determines if the login was successful
public bool Success {get;set;}
//the ID of the student, perhaps an int datatype would be better?
public string StudentID {get;set;}
//the error message (provided the login failed)
public string ErrorMessage {get;set;}
}
(尽管如此,你的主叫代码似乎已经知道了学生ID)
答案 2 :(得分:1)
删除其他人。只是做
if(result != null) {
...
}
return "Login Failed";
答案 3 :(得分:1)
如果出现以下情况,您还应该返回一些内容:
if (HashedPassword != result.Password)
在内部if中放入一个else
答案 4 :(得分:-2)
我在您的代码中进行了一些更改。试试吧。
public string Authentication(string studentID, string password)
{
var result = students.FirstOrDefault(n => n.StudentID == studentID);
var yourVar;
if (result != null)
{
byte[] passwordHash = Hash(password, result.Salt);
string HashedPassword = Convert.ToBase64String(passwordHash);
if (HashedPassword == result.Password)
{
//return result.StudentID;
yourVar = result.StudenID;
// if it does return the Students ID
}
}
else
//else return a message saying login failed
{
yourVar = "Login Failed";
}
return yourVar;
}