一個已經寫好的項目中有多個WebService,由于之前沒有記錄請求信息的,有時候需要查錯等需要找到當次的請求信息,所以需要加入記錄請求信息的功能。
首先想到的是在每一個帶有WebMethod特性的方法里調用記錄請求信息的方法,這樣可以記錄信息,但是太多帶WebMethod特性的方法了,于是想在全局中攔截并捕獲,于是想到了Global.asax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
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) { } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
[WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string QueryBalance(string username,string password) { if (username == "test" && password == "abcd") { return "1000000"; } else { return "用戶名或密碼錯誤"; } } |
這里使用了Log4Net將請求信息記錄起來
另一種調用方式是在另一個項目中添加了WerService的引用,
1
2
3
4
5
6
7
8
|
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")); } } |
以上這篇獲取WebService的請求信息方法實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/godbell/archive/2017/11/25/7897038.html