您的位置:首页 > 其它

使用VS.NET开发Web Services 简明教程

2004-08-01 00:57 1226 查看
使用VS.NET开发Web Services 简明教程 hbzxf(阿好) http://www.cnblogs.com/hbzxf 目录索引: 1 使用Visual Studio.NET 创建 Web Services 2 在 Web Forms 中调用 Web Services 3 在 Windows Forms中调用 Web Services 之所以称为简明教程,就是把简单的操作步骤一一列出,使初学者容易上手,对于复杂或相关的名词解释与服务原理可以参考相关的书籍,这里不再深谈。 第一节:使用Visual Studio.NET 创建 Web Services 1、 启动 Visual Studio.NET 2、 [文件]-[新建]-[项目]菜单,打开[新建项目]对话框,在[项目类型]中选择[Visual c# 项目],在[模板]中选择[ASP.NET Web 服务],如图1,

3、 更改默认位置为http://localhost/myservice,表示此web service位于http服务的myservice子目录下。 4、 点击确认,创建Web服务成功。 5、 切换到代码试图,你问我怎么切换,双击页面即可 6、 让我们逐行看看自动生成的代码含义 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; //上面一串子using就不必解释了 namespace myservice //建立命名空间,取的名字为我们建立的名字 { /// /// Service1 的摘要说明。 /// public class Service1 : System.Web.Services.WebService { public Service1() { //CODEGEN: 该调用是 ASP.NET Web 服务设计器所必需的 InitializeComponent(); } #region 组件设计器生成的代码 //Web 服务设计器所必需的 private IContainer components = null; /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion // WEB 服务示例 // HelloWorld() 示例服务返回字符串 Hello World // 若要生成,请取消注释下列行,然后保存并生成项目 // 若要测试此 Web 服务,请按 F5 键 // [WebMethod] // public string HelloWorld() // { // return "Hello World"; // } } } 7、 不妨把标注为斜体字的地方注释取掉,让我们在浏览器中看看是什么效果。别忘了,注释掉后需要重新编译。在浏览器中输入地址:http://localhost/myservice/Service1.asmx 可能看到如图2所示

8、 点击页面HelloWorld会看到方法返回字符串为HelloWorld,说明Web服务执行成功 9、 下面我们自己添加一个自定义的方法,功能返回一个DataSet,DataSet中存储为一个表信息,我们把返回的DataSet数据绑定到前台的DataGrid控件中。 10、由于涉及到了数据库的操作,所以我们需要在web.config中为webservices建立连接字符串,并且在Service1.asmx文件中把常用到的类对象初始化。 在web.config文件中添加数据库连接字符串如下,这里我们使用了SQLServer数据库: 在Service1.asmx中初始化数据库连接 1. 添加using System.Data.SqlClient; 注意结尾的分号 2. 定义全局对象变量 Protected SqlConnection conn; 3. 在构造函数中初始化连接对象和SqlConnection连接字符串 conn = new SqlConnection(); conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings[“connString”]; 11、 初始化好以后,开始自定义方法的代码,这里我们假定下面的方法功能返回northwind 数据库中名称为Employees的数据,详细代码如下。可以把代码拷贝到// WEB 服务示例 上面 /// /// 名称:GetEmployees /// 参数:无 /// 功能:检索Employees表中信息 /// 返回值:DataSet,返回检索出来的数据集。 /// [WebMethod(EnableSession=true,Description = "检索Employees表中信息。")] public DataSet GetEmployees () { try { DataSet ds=new DataSet(); string searchString="select * from Employees"; SqlDataAdapter da=new SqlDataAdapter(searchString,conn); da.Fill(ds,"Employees"); return ds; } catch { return null; } } 保存现在的Service1.asmx文件,重新编译运行查看此Webservices发现在HelloWorld的下方多出了新建的GetEmployees方法。接下来,我们开始把返回来的DataSet中的数据填充到前台DataGrid中。
详细操作请看第二节 在 Web Forms 中调用 Web Service
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: