c# - 更改 WCF Web Api HttpContext 响应

标签 c# xml wcf json wcf-web-api

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

  • 在内容正文中添加状态码字段
  • 将响应的状态码更改为 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;
   });

一个主要问题是不能同时处理xmlJson。我觉得必须有更好的方法来解决这个问题,因为这感觉很老套。

最佳答案

我不确定正确的方法,但我会尝试这样的事情:

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)中。

关于c# - 更改 WCF Web Api HttpContext 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6313461/

相关文章:

mysql - 创建mysql数据库并导入XML

wcf - 判断 WCF 服务是通过 HTTP 还是 HTTPS 调用的方法?

c# - Entity Framework : Serialize/Deserialize JSON column behind the scene

c# - 在 C# 中继承事件处理程序

xml - 哪种 XML 结构更有意义?

java - 需要澄清 Android 和应用程序架构中的 XML 文件

c# - WCF 双工回调,如何向所有客户端发送消息?

c# - Linq 查询不返回值

WCF NetTCPBinding 与 HttpBinding 在线发送数据的差异

NServiceBus 主机问题中的 WCF 服务托管