1

I am developing webapi in mvc4. I want to create a class which contains Custom HttpStatusCode which inherits HttpStatusCode class. Let's suppose I have one signup api which require user details like Firstname, Lastname, email, password etc. Suppose user enter email [email protected] and I check if user already exists. If this email is already exists I want to return Custom HttpStatusCode. Suppose I have created 1001 HttpStatusCode for email already exists.

I tried some thing like this

return new System.Web.Http.Results.ResponseMessageResult(
            Request.CreateErrorResponse(
                (HttpStatusCode)1001,
                new HttpError("Email is already exists.")
            )
        );

But I don't know is it a correct way or not. When we use return Unauthorized(); it means it's an unauthorized access which returns 401 error code. In same way I want to create a custom response and status code. In my case suppose email id already exists then I should return something like this return AlreadyExists() which return 1001 status code. Can I implement such a way? if yes, How can I implement this? can someone please help me?

4
  • 4
    Why are you inventing HTTP status codes? What do you expect the caller/client to do when it receives your weird 1001 status code? Commented Jan 5, 2015 at 11:28
  • @BenRobinson The one implementing the API should handle the new status codes then. Custom status codes help for specific errors, imho. Commented Jan 5, 2015 at 11:29
  • When it receive 1001 it means Email is already exists Commented Jan 5, 2015 at 11:29
  • You should not invent your own HTTP Status codes! - Find one that fits! Commented Jan 5, 2015 at 11:40

2 Answers 2

6

You shouldn't go about inventing new HTTP status codes. I'd say that at best it violates the Principle of Least Astonishment.

How about returning a response with an HTTP status code of 400 (Bad Request), and an error object that contains your application's error code and message?

Alternatively, you could use the overload of CreateErrorResponse that takes an exception argument.

Request.CreateErrorResponse(
    HttpStatusCode.BadRequest,
    new Exception("Email already exists.")
));

This results in the following JSON being returned from your endpoint:

{
    "Message":"An error has occurred.",
    "ExceptionMessage":"Email already exists.",
    "ExceptionType":"System.Exception",
    "StackTrace":null
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you reply. can I inherits HttpStatusCode class in c#?
HttpStatusCode is not a class, it is an enumeration (so you cannot inherit from it).
If you really really want to then you can use the unassigned HTTP status codes like 432-450 range for ClientError. You'll need to create HTTPResponseMessage and set its status code.
5

When we use return Unauthorized() [...] In my case suppose email id already exists then I should return something like this return AlreadyExists()

Unauthorized() is just a method in the base controller, you can add methods to your own controller:

public IHttpActionResult AlreadyExists()
{
    return new System.Web.Http.Results.ResponseMessageResult(
        Request.CreateErrorResponse(
            (HttpStatusCode)409,
            new HttpError("Already exists")
        )
    );
}

If you want to reuse it, add your own controller base class and let your controllers inherit from that:

public class MyApiController : ApiController
{
    public IHttpActionResult AlreadyExists()
    {
        return new System.Web.Http.Results.ResponseMessageResult(
            Request.CreateErrorResponse(
                (HttpStatusCode)409,
                new HttpError("Already exists")
            )
        );
    }
}

public class RegisterController : MyApiController
{
    // ...
}

And like the others said, don't go invent your own HTTP status codes.

8 Comments

Thank you for reply. When I call return AlreadyExists(); So it will return 409 status code right ?
Yesterday I tried 1001. It gives me an error related to range.
That is because 1001 is not a valid HTTP status code.
@AjayPunekar, find one that fits then... but either way, DO NOT TRY AND CREATE YOUR OWN!!
I am not opening the can of worms that is the discussion of "Which HTTP status code is the most appropriate in situation X", and that was not your question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.