VansFannel
VansFannel

Reputation: 46041

POST an invalid object: What HTTP STATUS Code do I have to return?

I'm developing a REST service using WCF and I don't know which type of HTTP Status Code do I have to return when I POST an invalid Message. Note: A message here is like a chat message (a text and some data).

This is how I have implemented the WCF Service:

IServiceContract:

[OperationContract]
[WebInvoke(Method = "POST",
    UriTemplate = "/messages",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare)]
Message AddMessage(Message message);

Service Implementation:

public Message AddMessage(Message message)
{
    OutgoingWebResponseContext ctx =
        WebOperationContext.Current.OutgoingResponse;

    if (message == null)
    {
        ctx.StatusCode = System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
        ctx.StatusDescription = "message parameter is null";

        throw new ArgumentNullException("message", "AddMessage: message parameter is null");
    }

    using (var context = new AdnLineContext())
    {
        context.Entry(message).State = EntityState.Added;
        context.SaveChanges();
    }

    return message;
}

Now I use RequestedRangeNotSatisfiable (HTTP 416). But I don't know if this is the HTTP Status code to return when I POST an invalid Message.

What kind of HTTP Status code do I have to return when I POST an invalid object?

Upvotes: 1

Views: 1973

Answers (2)

Witold Kaczurba
Witold Kaczurba

Reputation: 10515

From RFC7231 ( https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1 ):

6.5.1. 400 Bad Request

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Upvotes: 0

Joffrey Kern
Joffrey Kern

Reputation: 6499

Generally, you will use 4xx HTTP Status Code when you can manage an exception. Otherwise, you will generate a 5xx HTTP Status Code.

For your example, you can use the 400 Bad Request HTTP Status code.

10.4.1 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

From W3C

Upvotes: 3

Related Questions