在WCF Web API中使用HTTPResponseMessage返回“允许”实体标头

时间:2012-01-02 13:22:44

标签: wcf wcf-web-api

我正在尝试在响应消息中返回'Allow'实体标头,并且我不断收到以下消息:

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

以下是代码段:

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

任何建议都会非常有用。

谢谢,

多尔曼

1 个答案:

答案 0 :(得分:2)

尝试使用response.Content.Headers。