从C#中的Http Request对象中提取SOAP方法

时间:2013-03-05 15:52:18

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

我有一个日志记录方法,每次调用WebService时都会调用该方法,并用于记录有关该调用的信息。我需要能够提取为记录目的而调用的服务方法名称。

如何只使用传递给日志记录功能的HttpRequest对象来执行此操作?

   public static void LogApiCall(HttpRequest  httpRequest, string resultText = "Success", int resultCode = 0)
   {
      // Need to get the SOAP method named called from httpRequest here...
   }

更新

这是我最终使用的代码来自已接受的答案(稍加修改)。此代码已经过测试和验证,可以正常运行。

/// <summary>
/// Returns the Soap method name called from the http request object.
/// </summary>
public static string SoapMethod(HttpRequest httpRequest)
{

    var bodyRequest = XDocument.Parse(GetDocumentContents(httpRequest));

    if (bodyRequest.Root == null) 
        return httpRequest.Url.AbsoluteUri; 

    var element = bodyRequest.Root.Elements().Where(e => e.Name.LocalName == "Body").Elements().FirstOrDefault();

    return element != null ? element.Name.LocalName : httpRequest.Url.AbsoluteUri;
}

/// <summary>
/// Converts the input stream to a string for XML parsing.
/// </summary>
private static string GetDocumentContents(HttpRequest request)
{
    string documentContents;

    request.InputStream.Position = 0;
    using (var receiveStream = request.InputStream)
    {
        using (var readStream = new StreamReader(receiveStream, request.ContentEncoding))
        {
            documentContents = readStream.ReadToEnd();
        }
    }

    return documentContents;
}

1 个答案:

答案 0 :(得分:1)

public static void LogApiCall(HttpRequest httpRequest, string resultText = "Success", int resultCode = 0)
{

    XDocument bodyRequest = XDocument.Parse(GetDocumentContents(httpRequest));
    string methodName = bodyRequest.Root
                                    .Elements()
                                    .Where(e => e.Name.LocalName == "Body")
                                    .Elements()
                                    .FirstOrDefault().Name.LocalName;
}

private static string GetDocumentContents(HttpRequest request)
{
    string documentContents;
    using (Stream receiveStream = request.InputStream)
    {
        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
        {
            documentContents = readStream.ReadToEnd();
        }
    }
    return documentContents;
}