1

我正在使用 WCF 开发 REST 服务,但我不知道当我POST无效时必须返回哪种类型的 HTTP 状态代码Message。注意:此处的消息类似于聊天消息(文本和一些数据)。

这就是我实现 WCF 服务的方式:

服务合同

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

服务实施

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;
}

现在我使用RequestedRangeNotSatisfiable(HTTP 416)。但我不知道这是否是我 POST 无效时返回的 HTTP 状态代码Message

当我发布一个无效对象时,我必须返回什么样的 HTTP 状态代码?

4

2 回答 2

3

通常,当您可以管理异常时,您将使用 4xx HTTP 状态码。否则,您将生成 5xx HTTP 状态代码。

对于您的示例,您可以使用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.

来自W3C

于 2013-08-07T09:19:09.583 回答
0

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

6.5.1. 400 错误请求

400 (Bad Request) 状态码表示服务器不能或不会处理请求,因为某些东西被认为是客户端错误(例如,格式错误的请求语法、无效的请求消息帧或欺骗性请求路由)。

于 2017-02-13T09:18:30.860 回答