[英]Not all code paths return a value
我收到错误消息,并非所有代码路径都返回值?
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";
}
}
如果结果不是null,而是result.Password!= HashedPassword,则不返回任何内容。
您应该更改为以下内容:
...
if (HashedPassword == result.Password)
{
return result.StudentID;
// if it does return the Students ID
}
return "Invalid Password";
...
问题是由于嵌套的if语句,您的第一个if语句不能确保返回值。 想象一下,您将结果设置为一个值(非null),并且您的哈希密码和提供的密码不匹配,如果您遵循该逻辑,将无法命中return语句。
您应该将else子句添加到嵌套的if语句中,如下所示:
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语句无论如何都会终止该函数。 如果任何身份验证步骤失败,请尝试将此最终返回视为默认操作
在代码上要注意的另一点是,以这种方式返回混合数据不是理想的做法。 即结果可能是学生证,也可能是错误消息。 考虑创建一个具有多个属性的专用结果类,调用代码可以检查这些属性以查看逻辑验证的状态。 像下面这样的课程将是一个好的开始:
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;}
}
(尽管如此,您的调用代码似乎已经知道了该StudentID)
删除其他。 做就是了
if(result != null) {
...
}
return "Login Failed";
您还应该在以下情况下返回一些信息:
if (HashedPassword != result.Password)
如果在内部放置另一个
我对您的代码进行了一些更改。 试试吧。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.