我有一个安静的网络服务,返回的结果如下:
<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);
答案 0 :(得分:0)
我可以想到三个解决方案:
<强> 1。 Http模块(代码最少,但最容易引起维护)
假设您在ASP.Net中托管WCF,您可以创建一个Http模块,将\ r \ n添加到应用程序中所有响应的末尾。
这可能是Http模块的代码。我在这里使用'End'作为后缀,因为它在浏览器中比\ r更容易阅读,但对于\ r,你会将context_PostRequestHandlerExecute中的“End”更改为“\ r \ n”。
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。如果还没有,则需要在&lt; system.web&gt;&lt; httpModules&gt;中注册模块。部分。
<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为您提供了有关如何执行此操作的提示。我没有为此编写原型,因为看起来好像有许多方法需要被覆盖。我敢说他们中的大多数都是标准序列化器的非常简单的代表团。