我正在使用 SoapExtension 来记录 web 服务请求,以及 web 服务中发生错误时的响应。请求和响应 XMLDocument 的数据都不正确。有人可以查看代码以查看我可能做错了什么吗?如果我无法集中 SoapExtension 中的更改,那么我将着手在每个 Web 服务端点周围添加日志记录代码。
using System;
using System.IO;
using System.Web.Services.Protocols;
using System.Xml;
using Elmah;
public class ElmahSoapExtensionV2 : SoapExtension
{
private Stream oldStream;
private Stream newStream;
public static XmlDocument XmlRequest { get; private set; }
public static XmlDocument XmlResponse { get; private set; }
public override Stream ChainStream(Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage soapMessage)
{
switch (soapMessage.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
XmlRequest = GetSoapEnvelope(newStream);
if (soapMessage.Exception != null)
{
var exception = soapMessage.Exception.GetBaseException();
exception.Data.Add("SoapRequest", XmlRequest.OuterXml);
exception.Data.Add("SoapResponse", XmlResponse.OuterXml);
ErrorSignal.FromCurrentContext().Raise(exception);
}
CopyStream(newStream, oldStream);
break;
case SoapMessageStage.BeforeDeserialize:
CopyStream(oldStream, newStream);
XmlResponse = GetSoapEnvelope(newStream);
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
private static XmlDocument GetSoapEnvelope(Stream stream)
{
var xmlDocument = new XmlDocument();
stream.Position = 0;
var streamReader = new StreamReader(stream);
xmlDocument.LoadXml(streamReader.ReadToEnd());
stream.Position = 0;
return xmlDocument;
}
private static void CopyStream(Stream streamFrom, Stream streamTo)
{
var textReader = new StreamReader(streamFrom);
var textWriter = new StreamWriter(streamTo);
textWriter.WriteLine(textReader.ReadToEnd());
textWriter.Flush();
}
#region MyRegion
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type WebServiceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
#endregion
}