如何查看.NET 4.8中导入Connected Service生成的SOAP请求消息?
查看SOAP请求/响应消息的几种方法
方法1:通过配置文件启用WCF消息跟踪
WCF自带消息跟踪功能,可直接记录完整的SOAP内容,步骤如下:
- 在项目的
App.config或Web.config中,添加<system.diagnostics>节点配置:
<system.diagnostics> <sources> <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true"> <listeners> <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="soap_trace.log" /> </listeners> </source> </sources> </system.diagnostics>
- 运行程序发起SOAP请求后,项目输出目录会生成
soap_trace.log文件,用Visual Studio打开即可查看格式化后的SOAP请求与响应内容。
方法2:自定义消息检查器捕获SOAP内容
通过实现IClientMessageInspector接口,在请求发送前、响应接收后直接捕获SOAP消息,代码示例:
- 创建自定义检查器类:
public class SoapMessageInspector : IClientMessageInspector { public object BeforeSendRequest(ref Message request, IClientChannel channel) { // 复制请求消息避免原消息被消耗 var buffer = request.CreateBufferedCopy(int.MaxValue); var requestCopy = buffer.CreateMessage(); request = buffer.CreateMessage(); // 将SOAP请求内容输出到调试窗口 System.Diagnostics.Debug.WriteLine("SOAP 请求内容:\n" + requestCopy.ToString()); return null; } public void AfterReceiveReply(ref Message reply, object correlationState) { // 复制响应消息 var buffer = reply.CreateBufferedCopy(int.MaxValue); var replyCopy = buffer.CreateMessage(); reply = buffer.CreateMessage(); // 将SOAP响应内容输出到调试窗口 System.Diagnostics.Debug.WriteLine("SOAP 响应内容:\n" + replyCopy.ToString()); } }
- 创建行为类绑定检查器:
public class SoapMessageBehavior : IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.ClientMessageInspectors.Add(new SoapMessageInspector()); } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { } public void Validate(ServiceEndpoint endpoint) { } }
- 初始化客户端时附加行为:
var soapClient = new YourGeneratedSoapClient(); soapClient.Endpoint.Behaviors.Add(new SoapMessageBehavior()); // 调用服务方法 soapClient.YourServiceOperation();
运行后在Visual Studio的输出窗口即可查看完整的SOAP消息。
方法3:修复Fiddler配置查看SOAP内容
如果之前用Fiddler看不到具体SOAP内容,大概率是HTTPS解密未开启:
- 打开Fiddler,依次点击
Tools > Options > HTTPS,勾选Capture HTTPS CONNECTs和Decrypt HTTPS traffic,按提示安装根证书。 - 发起请求后,在Fiddler会话列表中找到目标请求,切换到
Inspectors标签页,选择XML或Raw视图即可查看完整SOAP XML内容。
内容的提问来源于stack exchange,提问作者Hursey
相关产品推荐
相关产品推荐

