Can we create custom HTTP Status codes? Can we create custom HTTP Status codes? asp.net asp.net

Can we create custom HTTP Status codes?


Yes, as long as you respect the class -- that is, 2xx for success, 4xx for Client error, etc. So you can return custom 4XX error codes (preferably those that are unassigned) for your own application's error conditions.

To quote from [RFC 2616][1]:

"HTTP status codes are extensible. HTTP applications are not required to understand the meaning of all registered status codes, though such understanding is obviously desirable. However, applications MUST understand the class of any status code, as indicated by the first digit, and treat any unrecognized response as being equivalent to the x00 status code of that class, with the exception that an unrecognized response MUST NOT be cached. For example, if an unrecognized status code of 431 is received by the client, it can safely assume that there was something wrong with its request and treat the response as if it had received a 400 status code."

Class'

  • 1xx: Informational - Request received, continuing process

  • 2xx: Success - The action was successfully received, understood, and accepted

  • 3xx: Redirection - Further action must be taken in order to complete the request

  • 4xx: Client Error - The request contains bad syntax or cannot be fulfilled

  • 5xx: Server Error - The server failed to fulfill an apparently valid request [1]:

http://tools.ietf.org/html/rfc2616#section-6.1.1


I recommend against creating your own HTTP status codes, when applicable codes already exist for the things that you want to do in your example.

From https://tools.ietf.org/html/rfc4918#section-11.2:

The 422 [Unprocessable Entity] status code means the server understands the content type of the request entity (hence a 415 [Unsupported Media Type] status code is inappropriate), and the syntax of the request entity is correct (thus a 400 [Bad Request] status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

It can be argued that "unable to process" could be due to a validation error.


Yes you can add custom error codes. If possible use codes that already exist though, and if you are declaring new ones be careful to avoid collisions.

You should be aware though that some proxies filter unknown codes. I had issues with users that where behind proxies that mapped 5XX to 500, and 4XX to 404. This made my ajax calls that where checking the status code to fail.