创建WebService的步骤:添加.asmx文件(Web服务),然后修改[WebMethod]下的方法来实现我们的功能。
发布WebService的步骤:发布网站->创建虚拟目录->浏览WebService页面(记下成功访问地址)->测试Web Service方法
具体操作步骤,在要添加WebService服务的工程建一个Web服务的文件,名字大概是WebService.asmx,然后在本工程的App_Code目录下,会看到该文件的后台CS文件。打开它,会看到如下代码:
Code
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyWebService : System.Web.Services.WebService
{
public MyWebService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string[] GetHotSearchByKeywords(string prefixText, int count)
{
return SearchKeywordManager.GetHotSearchKeywords(prefixText, count);
}
}
其中公布出来给远程调用的方法,我们在前面定义为[WebMethod],这个是关键。没了这个,远程没办法访问。然后再看看如何在远程调用这些方法,在远程的工程上,添加一个Web引用,注意,是Web引用,而不是服务引用。服务引用是WCF有关的。因为里面实现的具体方法不同。所以现在加的是Web方面的。然后指向刚才发布记下的那个地址,然后看后台代码
Code
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
lbList.Items.Clear();
MyS.MyWebService mws = new WinFormWeServiceTest.MyS.MyWebService();
string[] words= mws.GetHotSearchByKeywords(txtInput.Text.Trim(), 10);
foreach (string word in words) {
lbList.Items.Add(word);
}
}
//这里用了winform,其实其他项目引用大致相同,有空做个WPF方面的demo。首先先要在命名空间(刚添加引用指定的名称).出服务名称,然后实例化一个WebService引用。之后就可以调用里面的方法了。