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

时间:2010-04-06 20:14:12

标签: c# .net web-services soap asmx

示例:

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;
   }
}

4 个答案:

答案 0 :(得分:11)

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();
    }
}

答案 1 :(得分:7)

您还可以阅读contents of the Request.InputStream

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

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;
    }
  }
}

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

答案 2 :(得分:6)

是的,您可以使用SoapExtensions来完成。这是一个贯穿整个过程的nice article

答案 3 :(得分:1)

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

在这种情况下,您应该(暂时)enable trace logging on your service

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