使用WCF Web API之后,如何在应用程序逻辑已运行但返回给用户之前更改响应的内容主体。我们的目标是,如果抑制状态内容为true,我们:


将statuscode字段添加到内容主体
将响应的状态码更改为200


我已经覆盖了DelegatingChannel,在SendAsnyc中有一些看起来像这样的代码:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
                   {
                    return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(task =>
                    {
                        var response = task.Result;

                         if (CheckIfRequestHadSuppressStatusCode(request) == true)
                         {
                             string newResponse = (response.Content == null) ? "" : response.Content.ReadAsString();
                             newResponse = "<body>" +newResponse + "</body><statuscode>" + response.StatusCode + "</statuscode>";
                             response.StatusCode = HttpStatusCode.OK;
                         }

                        return response;
                    });


一个主要问题是这不能同时处理xml和Json。我觉得必须有一个更好的方法来解决该问题,因为这感觉很棘手。

最佳答案

我不确定正确的方法,但是我会尝试类似的方法,

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
        return base.SendAsync(request, cancellationToken)
            .ContinueWith<HttpResponseMessage>(task =>
               {
                var response = task.Result;

                if (CheckIfRequestHadSuppressStatusCode(request) == true)
                  {
                   switch(response.Content.Headers.ContentType.MediaType) {
                     case "application/xml":
                        response.Content = new XmlWithStatusContent(response.Content)
                        break;
                     case "application/json":
                        response.Content = new JsonWithStatusContent(response.Content)
                        break;
                  }

                  response.StatusCode = HttpStatusCode.OK;
                }

        return response; });


您可以封装在HttpContent的特殊版本中添加额外状态代码标记的代码(例如XmlWithStatusContent和JsonWithStatusContent)。

07-24 09:50