WCF WebApi, what is the correct way to handle IsThisTaken query?

245 Views Asked by At

I am in the process of writing a WCF webapi application and have a need to check whether an email address is taken or not. This needs to be a query the client-side code can do before attempting a PUT.

So, what I'm trying to do is use HEAD in conjunction with HTTP status codes. I am a little unsure how to go about doing that as it's a simple yes/no response which is required. So, I've used HttpResponseExceptions to return the relevant status code.

    [WebInvoke(Method = "HEAD", UriTemplate = "{email}")]
    [RequireAuthorisation]
    public void IsEmailAddressTaken(string email)
    {
        if (!Regex.IsMatch(email, Regexes.EmailPattern))
        {
            throw new RestValidationFailureException("email", "invalid email address");
        }

        if (_repository.IsEmailAddressTaken(email))
        {
            throw new HttpResponseException(HttpStatusCode.OK);
        }

        throw new HttpResponseException(HttpStatusCode.NoContent);
    }

This just doesn't "smell" right to me.

am I going about doing this kind of yes/no operation the right way?

2

There are 2 best solutions below

1
On BEST ANSWER

My suggestion is to return a HttpResponseMessage instead of throwing exceptions. Is your RestValidationFailureException being handled anywhere? If not, it will result in a 500 status code, which does not seem adequate.

1
On

I think it would be ok to just return OK for "exists" and 404 for "does not exist"