【问题标题】:Returning 'Allow' Entity Header with HTTPResponseMessage in WCF Web API在 WCF Web API 中使用 HTTPResponseMessage 返回“允许”实体标头
【发布时间】:2012-01-02 13:22:43
【问题描述】:

我正在尝试在响应消息中返回“允许”实体标头,但我不断收到以下消息:

{“无法添加标头。请确保将请求标头添加到HttpRequestMessage,将响应标头添加到HttpResponseMessage,并将内容标头添加到HttpContent对象。”}

这里是sn-p的代码:

 [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        public HttpResponseMessage<Order> DeleteOrder(int id)
        {
            HttpResponseMessage<Order> response = null;

            try
            {
                if (id <= 0)
                {
                    response = new HttpResponseMessage<Order>(HttpStatusCode.BadRequest);
                }
                else
                {
                    // For brevity, I'm assuming that order - 123456 was already served and logged. Hence it cannot
                    // be deleted. Order 12345, however, can be deleted.
                    // Note: The code doesn't actual delete anything. This is just a demonstration of
                    // the DELETE verb
                    if (id == 12345)
                    {                      
                        return new HttpResponseMessage<Order>(HttpStatusCode.NoContent);
                    }

                    if (id == 123456)
                    {                       
                        response = new HttpResponseMessage<Order>(HttpStatusCode.MethodNotAllowed);
                        response.Headers.AddWithoutValidation("Allow", "PUT");
                    }

                    // return '404 - Not Found' status code
                    response = new HttpResponseMessage<Order>(HttpStatusCode.NotFound);

                }

                return response;
            }
            catch (Exception ex)
            {
                return response = new HttpResponseMessage<Order>(HttpStatusCode.InternalServerError);
            }
        }

任何建议都会很有帮助。

谢谢,

多曼

【问题讨论】:

    标签: wcf wcf-web-api


    【解决方案1】:

    改用 response.Content.Headers。

    【讨论】:

    • 是的,成功了! :-) 当前文档没有提及任何内容。
    • 我认为这是因为在 RFC 中“允许”被称为“实体标头”,而其他则是响应标头。
    • 附带说明,如果您使用 MapServiceRoute,则无需明确指定 Method="Delete"。它将按照惯例从方法名称“DeleteOrder”中获取删除
    猜你喜欢
    • 2013-04-01
    • 2015-02-21
    • 2012-02-28
    • 1970-01-01
    • 2014-05-25
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多