Not all code paths return value while using Try Ca

2019-07-29 14:20发布

I have been getting "not all code paths return value" in the following code. I have the code below. I think I am returning appropriately but still there is an error.

[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);
    }
}

1条回答
劫难
2楼-- · 2019-07-29 15:11

You forgot a return statement in the first if statement.

[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);
    }
}
查看更多
登录 后发表回答