Get request information method instance of webservice

Time:2020-10-22

There are multiple WebServices in a project that has been written. Since there is no record of the request information before, sometimes it is necessary to check the error and find the current request information. Therefore, it is necessary to add the function of recording the request information.

The first thing I thought of was to call a method to record the request information in every method with webmethod feature, so that information could be recorded. But there are too many methods with webmethod feature. So I wanted to intercept and capture in the global, so I thought Global.asax


public class Global : System.Web.HttpApplication
 {

  protected void Application_Start(object sender, EventArgs e)
  {

  }

  protected void Session_Start(object sender, EventArgs e)
  {

  }

  protected void Application_BeginRequest(object sender, EventArgs e)
  {
   if (Request != null)
   {
    try
    {
     if (".asmx".Equals(Request.CurrentExecutionFilePathExtension,StringComparison.OrdinalIgnoreCase) && Request.ContentLength > 0)
     {
      using (MemoryStream ms = new MemoryStream())
      {
       Request.InputStream.CopyTo(ms);
       ms.Position = 0;
       using (StreamReader reader = new StreamReader(ms))
       {
        LogHelper.Info(reader.ReadToEnd());
       }
      }
      
     }
     
    }
    catch (Exception)
    {
    }
    finally
    {
     Request.InputStream.Position = 0;
    }
   }
  }

  protected void Application_AuthenticateRequest(object sender, EventArgs e)
  {

  }

  protected void Application_Error(object sender, EventArgs e)
  {

  }

  protected void Session_End(object sender, EventArgs e)
  {

  }

  protected void Application_End(object sender, EventArgs e)
  {

  }
 }
[WebMethod]
public string HelloWorld()
{
 return "Hello World";
}
[WebMethod]
public string QueryBalance(string username,string password)
{
 if (username == "test" && password == "abcd")
 {
  return "1000000";
 }
 else
 {
  Return "wrong user name or password";
 }
}

Log4net is used to record the request information

Another way is to add a reference to werservice in another project,


public partial class WebForm1 : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
  {
   TestWebServiceSoapClient client = new TestWebServiceSoapClient();
   Response.Write(client.QueryBalance("test","abcd"));
  }
 }

The above example of how to obtain the request information of WebService is the whole content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developeppaer more.