獲取WebService的請求信息


一個已經寫好的項目中有多個WebService,由於之前沒有記錄請求信息的,有時候需要查錯等需要找到當次的請求信息,所以需要加入記錄請求信息的功能。

首先想到的是在每一個帶有WebMethod特性的方法里調用記錄請求信息的方法,這樣可以記錄信息,但是太多帶WebMethod特性的方法了,於是想在全局中攔截並捕獲,於是想到了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)
        {

        }
    }
View Code

 

 

[WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string QueryBalance(string username,string password) { if (username == "test" && password == "abcd") { return "1000000"; } else { return "用戶名或密碼錯誤"; } }
View Code

這里使用了Log4Net將請求信息記錄起來

 

 

另一種調用方式是在另一個項目中添加了WerService的引用,

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")); } }
View Code

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM