更改 WCF WebApi HttpContent 响应 [英] Change WCF WebApi HttpContent response

查看:13
本文介绍了更改 WCF WebApi HttpContent 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the WCF Web API how would I go about changing a response's content body after the application logic has been run but before it's returned to the user. The goal is if suppressstatuscontent is true we:

  • 向内容正文添加状态码字段
  • 将响应中的状态码更改为 200

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

I have overridden a DelegatingChannel and in the SendAsnyc have some code that looks like this:

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.我觉得必须有更好的方法来解决这个问题,因为这感觉很hacky.

A major problem is this doesn't handle BOTH, xml and Json. I feel like there must be a much better way to go about the problem as this feels very hacky.

推荐答案

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

I'm not sure of the right approach but I would try something like this:

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)中封装添加额外状态代码标记的代码.

You can encapsulate the code that adds the extra status code markup in specialized versions of HttpContent (e.g. XmlWithStatusContent and JsonWithStatusContent).

这篇关于更改 WCF WebApi HttpContent 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆