有没有办法从ASP.NET WebMethod中获取原始SOAP请求?

例:

public class Service1 : System.Web.Services.WebService { [WebMethod] public int Add(int x, int y) { string request = getRawSOAPRequest();//How could you implement this part? //.. do something with complete soap request int sum = x + y; return sum; } } 

SoapExtensions的另一种替代方法是实现IHttpModule并在输入流时获取输入流。

 public class LogModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += this.OnBegin; } private void OnBegin(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; byte[] buffer = new byte[context.Request.InputStream.Length]; context.Request.InputStream.Read(buffer, 0, buffer.Length); context.Request.InputStream.Position = 0; string soapMessage = Encoding.ASCII.GetString(buffer); // Do something with soapMessage } public void Dispose() { throw new NotImplementedException(); } } 

是的,你可以使用SoapExtensions来做到这一点。 这是一篇贯穿整个过程的精彩文章 。

您还可以读取Request.InputStream的内容 。

这种方式更有用,例如您希望根据输入内容在WebMethod中执行validation或其他操作的情况。

 using System; using System.Collections.Generic; using System.Web; using System.Xml; using System.IO; using System.Text; using System.Web.Services; using System.Web.Services.Protocols; namespace SoapRequestEcho { [WebService( Namespace = "http://soap.request.echo.com/", Name = "SoapRequestEcho")] public class EchoWebService : WebService { [WebMethod(Description = "Echo Soap Request")] public XmlDocument EchoSoapRequest(int input) { // Initialize soap request XML XmlDocument xmlSoapRequest = new XmlDocument(); // Get raw request body Stream receiveStream = HttpContext.Current.Request.InputStream // Move to begining of input stream and read receiveStream.Position = 0; using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { // Load into XML document xmlSoapRequest.Load(readStream); } // Return return xmlSoapRequest; } } } 

注意:更新以反映下面的约翰斯评论。

我假设您要记录SOAP请求以进行跟踪; 也许你有一个服务的消费者告诉你他们正在给你发送好的SOAP,但是你不相信它们,是吗?

在这种情况下,您应该(暂时) 启用服务上的跟踪日志记录 。

如果您正在尝试进行通用日志记录,请不要使用SOAP数据包,因为它很重; 你的日志会很快膨胀。 只需记录重要内容,例如“添加被叫,X = foo,Y =条形”。