我有一个每次调用 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;
}