我一直在"并非所有代码路径都返回值"在以下代码中。我有下面的代码。我想我正在适当地回来,但仍然有错误。
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
答案 0 :(得分:1)
你在第一个if语句中忘记了一个return语句。
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
-->return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}