web service类什么时候初始化?
下面的这个例子演示了web service是如何初始化的:
1.创建测试用的web service.
注意:必须给对应的目录添加对ASPNET帐号的写权限,否则会出现访问拒绝的异常.
2.创建客户端测试代码
1.创建测试用的web service.
1
using System;
2
using System.Web;
3
using System.Web.Services;
4
using System.Web.Services.Protocols;
5
using System.IO;
6
7
[WebService(Namespace = "http://tempuri.org/")]
8
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
9
public class Service : System.Web.Services.WebService
10
{
11
private static int counter = 0;
12
public Service()
13
{
14
15
//Uncomment the following line if using designed components
16
//InitializeComponent();
17
counter++;
18
using (System.IO.StreamWriter w = File.AppendText(@"c:\a\time.txt"))
19
{
20
w.WriteLine("You have called this webservice " +counter.ToString() + " times, the lates call happened at: " + DateTime.Now.ToString());
21
}
22
23
}
24
25
[WebMethod]
26
public string HelloWorld(string name)
27
{
28
//currentMethod = "HelloWord";
29
return "Hello World: " + name;
30
}
31
[WebMethod]
32
public string Welcome(string name)
33
{
34
return "Welcome: " + name;
35
}
36
37
}
38
从代码中可以看出,在服务器的构造函数中只是在一个文件中记录了当前服务器的时间和一共调用了web service的次数.
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

注意:必须给对应的目录添加对ASPNET帐号的写权限,否则会出现访问拒绝的异常.
2.创建客户端测试代码
1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Data;
5
using System.Drawing;
6
using System.Text;
7
using System.Windows.Forms;
8
using System.Net;
9
10
namespace WSTest
11
{
12
public partial class Form1 : Form
13
{
14
localhost.Service s = null;
15
public Form1()
16
{
17
InitializeComponent();
18
s = new localhost.Service();
19
}
20
21
private void btnHelloWorld_Click(object sender, EventArgs e)
22
{
23
MessageBox.Show(s.HelloWorld("zzq"));
24
}
25
26
private void btnWelcome_Click(object sender, EventArgs e)
27
{
28
MessageBox.Show(s.Welcome("zzq"));
29
}
30
31
32
}
33
}

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

只是一个简单的win form程序,你可以通过两个按钮按不同的次序调用两个web method,然后看生成的文件里记录的信息.
3.下面是生成的文本文件的截图.
.
4. 结论
web service在每一个请求来之前都会重新初始化一次,每调用其中的一个web method都会造成web service被重新初始化.