Home > Enterprise >  REST API check if email exists
REST API check if email exists

Time:12-18

I would like to check if the user exists with the email in the database. I want to do this in the API, it should simply return true or false. This is what i get; when the user exists it returns true if the user does not exist in DB it returns a 500 internal server error. How could I solve this? Thanks in advance

    public IHttpActionResult GetUserEmail(string Email)
    {
        var User = (db.Users
        .Where(p => p.Email == Email)
        .First());

        if (User == null)
        {
            return Ok(false);
        }
        else
        {
            return Ok(true);
        }
    }

CodePudding user response:

The answer has been given above, I am leaving an example code block just as an example. :)

    var User = db.Users.FirstOrDefault(p => p.Email == Email);
    if (User == null)
        {
            return Ok(false);
        }
        else
        {
            return Ok(true);
        }

// or

 var User = db.Users.Any(p => p.Email == Email);
 if (!User)
 {
   return Ok(false);
 }
 else
 {
  return Ok(true);
 }

CodePudding user response:

code block with the changes as mentioned by @Dawood Awan in the comments –

public IHttpActionResult GetUserEmail(string Email)
{
    var User = (db.Users
    .Where(p => p.Email == Email)
    .FirstOrDefault());

    if (User == null)
    {
        return Ok(false);
    }
    else
    {
        return Ok(true);
    }
}
  • Related