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

Fra*_*ega 9 .net c# soap web-services 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;
   }
}
Run Code Online (Sandbox Code Playgroud)

niv*_*lam 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 可能很明显,但您可能需要在web.config中注册IHttpModule <system.webServer> <modules> <add name ="LogModule"type ="MyNameSpace.LogModule"/> </ modules> </system.webServer> (2认同)

Ste*_*las 7

您还可以读取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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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


Eri*_*lje 6

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

  • 链接坏了. (4认同)