【问题标题】:How can I add characters at the end of my xml response?如何在我的 xml 响应末尾添加字符?
【发布时间】:2013-07-26 19:55:41
【问题描述】:

我有一个安静的网络服务,它返回如下结果:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Some Text</string> 

但是,接收端的人需要使用特殊字符(例如“\r”)来终止此文本。如何将该文本添加到序列化响应的末尾?

我从 C# 中的 WCF 服务内部发送此响应,如下所示:

[WebGet(UriTemplate = "/MyMethod?x={myId}"), OperationContract]
string GetSomeText(Guid myId);

【问题讨论】:

  • 您使用什么技术来创建回复?
  • 恕我直言,这听起来像是来自您客户的古怪要求。您正在返回一个有效的 XML sn-p - 这对他们来说应该足够好了,恕我直言。

标签: web-services serialization


【解决方案1】:

我能想到三个解决方案:

1. Http 模块(代码最少但维护最混乱)

假设您在 ASP.Net 中托管 WCF,您可以创建一个 Http 模块以在应用程序中所有响应的末尾添加一个 \r。

这可能是 Http 模块的代码。我在这里使用了 'End' 作为后缀,因为它在浏览器中比 \r 更容易阅读,但是对于 \r,您可以将 context_PostRequestHandlerExecute 中的“End”更改为“\r”。

public class SuffixModule : IHttpModule
{
    private HttpApplication _context;

    public void Init(HttpApplication context)
    {
        _context = context;
        _context.PostRequestHandlerExecute += context_PostRequestHandlerExecute;
    }



    void context_PostRequestHandlerExecute(object sender, EventArgs e)
    {
        // write the suffix if there is a body to this request
        string contentLengthHeaderValue = _context.Response.Headers["Content-length"];
        string suffix = "End";
        if (!String.IsNullOrEmpty(contentLengthHeaderValue))
        {
            // Increase the content-length header by the length of the suffix
            _context.Response.Headers["Content-length"] = 
                        (int.Parse(contentLengthHeaderValue) + suffix.Length)
                        .ToString();
            // and write the suffix!
            _context.Response.Write(suffix);
        }

    }

    public void Dispose()
    {
        // haven't worked out if I need to do anything here
    }
}

然后你需要在你的 web.config 中设置你的模块。下面假设您的 IIS 在集成管道模式下运行。如果还没有,则需要在 部分中注册模块。

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <!-- 'type' should be the fully-qualified name of the type, 
followed by a comma and the name of the assembly-->
    <add name="SuffixModule" type="WcfService1.SuffixModule,WcfService1"/>
  </modules>
 </system.webServer>

这个选项的问题是它会默认影响应用程序中的所有请求,如果你决定使用分块编码,它可能会失败。

2。使用 ASP.NET MVC(改变技术但良好的可维护性)

使用 MVC 而不是 WCF。你可以更好地控制你的输出。

3.自定义序列化器(大量代码,但不如选项 1 hacky)

您可以编写自己的自定义序列化程序。 This StackOverflow question 为您提供有关如何执行此操作的指示。我没有为此编写原型,因为它看起来好像有很多很多需要重写的方法。我敢说它们中的大多数都是标准序列化程序的非常简单的委托。

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2022-06-20
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多