最简单的webservice如何写

最简单的webservice如何写,第1张

在开始下面这个例子之前,你的系统需要:

1、WIN2000 + IIS;

2、VS.Net;

3、SQL Server(我这里用的是SQL数据库);

这个Web Service的例子用的是MS大吹的C#写的,如果你喜欢VB,那么用VB也是一样的哦,只不过语法上一些小的差别而已,道理都是一样的,不过即然MS都鼓吹C#,如果你能够用C#写还是用这为好哦。

下面是写的步骤:

一、打开VS。NET的集成开发环境,FILE菜单上选择New,新建一个C#的ASP.NET Web Service工程,工程名为WebServiceDemo(完整的是http://localhost/WebServiceDemo)。这是VS就在你的Web系统目录下生成了相应的文件,我的服务目录是默认的c:\Inetpub\wwwroot,生成的文件就在c:\Inetpub\wwwroot\webserviceDemo下,就不多说了。

二、打开与生成工程对应的C#源文件,这里是Service1.asmx.cs,VS.Net集成环境已经为你生成了相应的代码如下:

// =============================================================================

// 文件: Service1.asmx.cs

// 描述: 架构一个Web Service来对数据库进行互访

//

//

// ============================================================================

using System

using System.Collections

using System.ComponentModel

using System.Data

using System.Diagnostics

using System.Web

using System.Web.Services

using System.Data.SqlClient

// 系统生成了与工程名相同的命名空间

namespace WebServiceDemo

{

/// <summary>

/// Summary description for Service1.

/// </summary>

// 所有的WEB服务都是派生于System.Web.Services.WebService的。

public class Service1 : System.Web.Services.WebService

{

public Service1()

{

//CODEGEN: This call is required by the ASP.NET Web Services Designer

InitializeComponent()

}

}

}

里面我添加了文件说明和相应的注释,接下来就是在里面编写相应的服务代码了。这里我想先把对数据库的 *** 作封装在同一命名空间的单独的一个类里,下面编写WEB方法时只用接调用这个类中的相应方法就可以了。下面是我写的这个类的代码:

// -------------------------------------------------------------------------

// 构建一个新类,用于对数据的访问

// -------------------------------------------------------------------------

public class DataAccess

{

// 连接字符串成员变量

private string m_szConn = ""

private SqlConnection m_sqlConn

private SqlDataAdapter m_sqlDa

// 构造函数

public DataAccess(string szConnectionString)

{

m_szConn = szConnectionString

}

// 返回一个记录集

public DataSet GetDataset(string szCommandText)

{

DataSet sqlDs

try

{

m_sqlConn = new SqlConnection(m_szConn)

m_sqlConn.Open()

m_sqlDa = new SqlDataAdapter(szCommandText,m_sqlConn)

sqlDs = new DataSet()

m_sqlDa.Fill(sqlDs)

m_sqlConn.Close()

return sqlDs

}

catch

{

return null

}

}

// 重载上述方法

public DataSet GetDataset(string szCommandText, string szTableName)

{

DataSet sqlDs

try

{

m_sqlConn = new SqlConnection(m_szConn)

m_sqlConn.Open()

m_sqlDa = new SqlDataAdapter(szCommandText,m_sqlConn)

sqlDs = new DataSet()

m_sqlDa.Fill(sqlDs,szTableName)

m_sqlConn.Close()

return sqlDs

}

catch

{

return null

}

}

}

这些就不多说了,与创建一般的C#类是一样的。类中有三个函数,其中一个为构造函数,调用时传入连接字符串。另外两个函数都是一样的作用,返回用户需要的记录集,只不是调用时传的参数不一样,实质都是一样的。

下面就是在Service1类中添加真正用于WEB调用的代码了,这部分才是给WEB应用程序调用的东西。在编写这个类的代码之前,应该先申请一个服务命令空间,设置相应的属性,这一句可万万不能少哦,呵呵~,它告诉了WEB服务存放的路径等相关的信息。如下:

// 声明一个服务空间

[WebService(

Namespace = "http://localhost/WebServiceDemo/", //其实这个才是最重要的啦~,其它的都可以不要哦

Name= "Web Service Demo",

Description = "Web Service Demo"

)]

下面是Service1的代码:

public class Service1 : System.Web.Services.WebService

{

public Service1()

{

//CODEGEN: This call is required by the ASP.NET Web Services Designer

InitializeComponent()

}

#region Component Designer generated code

//Required by the Web Services Designer

private IContainer components = null

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

}

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose( bool disposing )

{

if(disposing &&components != null)

{

components.Dispose()

}

base.Dispose(disposing)

}

#endregion

// 连接字符串常量

const string szConn = "server=(local)\\taoyiuid=sapwd="

+ "initial catalog=mydatadata source=taoyi"

[WebMethod]

public String About()

{

return "这是一个C#编写的Web Service演示程序!"

}

// 返回其中一个WebServiceDemo表

[WebMethod]

public DataSet GetServiceDemoTable()

{

DataSet sqlDs = new DataSet()

DataAccess dataAcc = new DataAccess(szConn)

string szSql = "Select * From WebServiceDemo"

sqlDs = dataAcc.GetDataset(szSql,"Demo")

return sqlDs

}

// 返回由用户指定的查询

[WebMethod]

public DataSet GetByUser(string szCommandText)

{

DataSet sqlDs = new DataSet()

DataAccess dataAcc = new DataAccess(szConn)

sqlDs = dataAcc.GetDataset(szCommandText)

return sqlDs

}

}

是不是很简单哦,就只这么点,呵呵~,不过也可以说明问题的了。这个类中声明了三个WEB方法,有没有发觉呢?每个方法的前面都加了[WebMethod],表示该方法为WEB方法。呵呵,如果你想要你写的函数可以让WEB应用程序调用的话,这个可不能少的啦~,不然WEB应用程序就无法调用的。

到此一个WEB服务就完成了,点击运行看看,如果没什么错的话,就会出现如下的WEB页面服务描述:

Service1

The following operations are supported. For a formal definition, please review the Service Description.

* GetByUser

* GetServiceDemoTable

* About

.....(下面还有很多)

其中代星号的就是先前在函数前加了[WebMethod]的函数。在出现在页面中你可以单击相应的函数,然后就会跳到调用页面,你可以在相应的文本框中(如果函数有参数的话)输入相应的参数,点而调用按钮,那么就可以看到函数返回的结果了(前提是函数调用无错的话),不过全是XML格式的文本。比如我的GetServiceDemoTable函数调用的结果如下:

<?xml version="1.0" encoding="utf-8" ?>

- <DataSet xmlns="http://tempuri.org/">

- <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

- <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:Locale="zh-CN">

- <xs:complexType>

- <xs:choice maxOccurs="unbounded">

- <xs:element name="Demo">

- <xs:complexType>

- <xs:sequence>

<xs:element name="ID" type="xs:int" minOccurs="0" />

<xs:element name="szUser" type="xs:string" minOccurs="0" />

<xs:element name="szSex" type="xs:string" minOccurs="0" />

<xs:element name="szAddr" type="xs:string" minOccurs="0" />

</xs:sequence>

</xs:complexType>

</xs:element>

</xs:choice>

</xs:complexType>

</xs:element>

</xs:schema>

- <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">

- <NewDataSet xmlns="">

- <Demo diffgr:id="Demo1" msdata:rowOrder="0">

<ID>1</ID>

<szUser>taoyi</szUser>

<szSex>男</szSex>

<szAddr>四川泸州</szAddr>

</Demo>

- <Demo diffgr:id="Demo2" msdata:rowOrder="1">

<ID>2</ID>

<szUser>xiner</szUser>

<szSex>女</szSex>

<szAddr>四川宜宾</szAddr>

</Demo>

</NewDataSet>

</diffgr:diffgram>

</DataSet>

到此为至,Web Service程序就已经算是完成了。

下面要做的是写一个WEB应用程序来测试我写的这个Web Service了,看看能不能达到想要的结果。建立Web应用程序的步骤如下:

一、新建一个ASP.Net Web Application工程,与创建Web Service的第一步一样,只是工程类型不一样罢了。我这里工程名为WebServiceDemoTest,完整的为http://localhost/WebServiceDemoTest,系统就在相应的目录(c:\Inetpub\wwwroot\WebserviceDemoTest)下生成了所需文件。

二、在设计视图下打开WebForm1.aspx文件,在里面放置一个panel容器,为了达到测试的目的,我们需要三个服务端按钮和一个服务端文本框,分别调用我们在Web Service中写的三个函数,另外,为了展示调用方法所得达的数据,还需要一个服务端标签控件和一个DataGrid控件。页面的布置就随便你了,想怎么放置就怎么放置,只要能达到演示的目的就行。

三、引用先前写的Web Service程序,菜单步骤如下project->add web reference...,然后输入我们Web Service的路径,这里是http://localhost/WebServiceDemo/Service1.asmx,点击添加就OK了。这时你将在类视图中看到localhost命名空间了。

四、编写测试代码。

为了便于后面少写些代码,如(xxxx.xxxx.xx xx = new xxxx.xxx.xx()这种),那么首先你得引用localhost命名空间的service1类,以后直接写xxxx xx = new xxxx()就可以了。

下面是几个按钮的代码:

// 测试GetServiceDemoTable()

private void Button2_Click(object sender, System.EventArgs e)

{

DataSet ds = new DataSet()

Service1 oService = new localhost.Service1()

// 返回记录集

ds = oService.GetServiceDemoTable()

if (ds != null)

{

// 显示记录集的记录

DataGrid1.DataSource = ds.Tables["Demo"]

DataGrid1.DataBind()

}

else

{

this.Response.Write("加载数据错误!")

}

}

// 测试GetByUser()

private void Button1_Click(object sender, System.EventArgs e)

{

DataSet ds = new DataSet()

Service1 oService = new localhost.Service1()

String szCommand = TextBox1.Text

ds = oService.GetByUser(szCommand)

if (ds != null)

{

DataGrid1.DataSource = ds

DataGrid1.DataBind()

}

else

Response.Write("错误!有可能是SQL命令有问题!")

}

// 测试About()

private void Button3_Click(object sender, System.EventArgs e)

{

Service1 oService = new localhost.Service1()

Label1.Text = oService.About()

}

OK,最后就是运行了,如果一切OK,点击第一个按钮得到的将是在一个包函用户执行的SQL命令的表结果。第二个按钮得到的就是上面运行Web Service时的GetServiceDemoTable得到的XML描述,即

ID szUser szSex szAddr

1 taoyi 男 四川泸州

2 xiner 女 四川宜宾

点击第三个按钮,则在Label1中显示"这是一个C#编写的Web Service演示程序!”的字符串

WebService目前可是目前计算机界一个非常流行的技术了 以至于有些人把WebService列入目前最热门的十大技术之一 的确随着互联网的广泛应用和发展 尤其是电子商务的发展 出于互联网上各种复杂的应用系统和对更高安全性的要求 WebService的横空出世的确满足了当前这些的要求和需要 其中的原因在下文中有详细的介绍 本文的主要内容是简要介绍一下WebService的相关知识 以及使用VisualBasic Net实现WebServices的具体方法和典型步骤

一 WebService为何物 我们为什么需要它

WebService的主要功能就是可以实现实现跨平台的功能调用 同时由于WebService中使用XML来进行数据交换 所以在使用WebService时不用担心防火墙的影响 由于WebService集成了各种功能 并提供了一个友好的界面 所以在WebService能够实现软件的重用

另外WebService的调用非常简单 简而言之调用互联网上的WebService就如同调用本地的组件一样简单 就是通过HTTP协议来调用互联网上的组件 至于具体的调用方法 请参阅本文第五节第七段的内容 所以Web Service就是互联网上的组件调用

二 和Web Service相关的标准 协议

Web Service是通过一系列标准和协议来保证和程序之间的动态连接和实现其安全调用的 其中主要的标准和协议是 XML WSDL SOAP HTTP UDDI 下面就简要介绍这些标准和协议

XML Web Service之间和Web Service和应用程序之间都是采用XML进行数据交换的 Web Service由于基于了XML 这样Web Service在具备XML带来的优势的同时 也拥有了由于XML所带来的缺点 其中XML所带来的最重要缺点就是Web Service将大量的占有CPU的资源 因为XML数据要经过多步处理才能被系统使用 所以 即使调用一个功能较小的Web Service 也会感觉速度很慢 所以网络中对运行Web Service的主机要求是很高的

HTTP 应用程序是提供HTTP协议来调用Web Service的 所以HTTP在Web Service调用过程中 起著通道的作用

WSDL 是Web Service描述语言的简写 它是XML格式 其作用是描述Web Service 指示应用程序和与Web Servie交互的方法 当实现了某种Web Service服务时 为了让别的程序调用 就必须告诉此Web Service的接口 如 服务名称 服务所在的机器名称 监听端口号 传递参数的类型等等 WSDL就是规定了有关Web Services描述的标准

UDDI 是Universal Description Discovery and Integration的缩写 简单说 UDDI用于集中存放和查找WSDL描述文件 起著目录服务器的作用

SOAP 是 Simple Object Access Protocol 的缩写 即 简单对象访问协议 SOAP是一种消息传递的协议 它规定了Web Services之间传递信息的方式

三 本文章的程序设计 调试和运行的环境

( ) 微软公司视窗 中文企业版

( ) Visual Studio Net 企业构建版 Net FrameWork SDK 版本号

( ) IIS服务启动

四 Visual Basic Net实现Web Service

Net 的大的推动了Web Service的发展 而Visual Studio Net的出现又极大的推动了Web Service的的广泛应用 在Visual Studio Net推出之前 编写一个Web Service是一项非常复杂的工作 同样调用这个Web Service也十分麻烦 由于Visual Studio Net对Web Service提供了较强的支持 很多细致 烦杂的工作都由Visual Studio Net自动完成了 这样就使得上述工作变得非常简单 甚至不了解Web Service和其相关的标准 协议 也可以使用Visual Studio Net编写Web Service 并使用这个Web Service 下面就来用Visual Basic Net实现一个Web Service 此Web Service和数据库相关 数据库类型选用的是Sql Server 此Web Service提供了二个函数功能调用 其一名称为Binding 用以实现数据绑定 其二名称为Update 用以更新数据库中的数据

以下就是Visual Basic Net实现此Web Service的具体步骤

启动Visual Studio Net

选择菜单「文件」|「新建」|「项目」后 d出「新建项目」对话框

将「项目类型」设置为「Visual Basic项目」

将「模板」设置为「ASP NET Web 服务」

在「位置」的文本框中输入//localhost/UpdateDataWebService 后 单击「确定」按钮 这样在Visual Studio Net就会计算机Internet信息服务的默认目录中创建一个名称为 UpdateDataWebService 文件夹 里面存放的是此项目的文件 具体如图 所示

图 创建Web Service项目对话框

选中「解决方案资源管理器」中的 Service a *** x 文件 单击鼠标右键 在d出的菜单中选择「查看代码」 则进入Service a *** x vb的编辑界面

在Service a *** x……vb的首部 在导入命名空间的代码区中添加下列代码 下列代码作用是导入命名空间System Data SqlClient

Imports System Data SqlClient

在Service a *** x……vb文件的 Public Class Service Inherits System Web Services WebService 代码后 添加下列代码 下列代码是在Web Service中定义二个功能调用

<WebMethod ( ) >Public Function Binding ( ) As DataSet Dim con As New SqlConnection ( Server = localhost uid = sa pwd = database = northwind ) Dim daCust As New SqlDataAdapter ( Select * From Customers con ) Dim ds As New DataSet ( ) daCust Fill( ds Cust ) Return dsEnd Function<WebMethod ( ) >Public Function Update ( ByVal ds As DataSet ) As DataSet Dim con As New SqlConnection ( Server = localhost uid = sa pwd = database = northwind ) Dim daCust As New SqlDataAdapter ( Select * From Customers con ) Dim cbCust As New SqlCommandBuilder ( daCust ) daCust Update ( ds Cust ) Return dsEnd Function

保存上述的修改 一个简单的 *** 作Sql Server数据库的Web Service就完成了 此时单击快捷键F 此Web Service就开始运行 并可以对外提供服务了 具体如图 所示:

图 :Web Service提供服务是的界面

Service a *** x vb的代码清单如下:

Imports System Web ServicesImports System Data SqlClient<WebService ( Namespace := ) >_Public Class Service Inherits System Web Services WebService<WebMethod ( ) >Public Function Binding ( ) As DataSet Modify this Connection string to use your SQL Server and log on  Dim con As New SqlConnection ( Server=localhostuid=sapwd=database=northwind ) Dim daCust As New SqlDataAdapter ( Select * From Customers con ) Dim ds As New DataSet ( ) daCust Fill ( ds Cust ) Return dsEnd Function<WebMethod ( ) >Public Function Update ( ByVal ds As DataSet ) As DataSet Dim con As New SqlConnection ( Server=localhostuid=sapwd=database=northwind ) Dim daCust As New SqlDataAdapter ( Select * From Customers con ) Dim cbCust As New SqlCommandBuilder ( daCust ) daCust Update ( ds Cust ) Return dsEnd Function#Region Web 服务设计器生成的代码 Public Sub New ( ) MyBase New ( )  该调用是 Web 服务设计器所必需的  InitializeComponent ( )  在 InitializeComponent ( ) 调用之后添加您自己的初始化代码End Sub Web 服务设计器所必需的Private ponents As System ComponentModel IContainer  注意 以下过程是 Web 服务设计器所必需的  可以使用 Web 服务设计器修改此过程   不要使用代码编辑器修改它  <System Diagnostics DebuggerStepThrough ( ) >Private Sub InitializeComponent ( ) ponents = New System ComponentModel Container ( )End SubProtected Overloads Overrides Sub Dispose ( ByVal disposing As Boolean ) CODEGEN: 此过程是 Web 服务设计器所必需的 不要使用代码编辑器修改它 If disposing Then If Not ( ponents Is Nothing ) Thenponents Dispose ( ) End IfEnd IfMyBase Dispose ( disposing )End Sub#End Region Web 服务示例 HelloWorld ( ) 示例服务返回字符串 Hello World 若要生成项目 请取消注释以下行 然后保存并生成项目 若要测试此 Web 服务 请确保 a *** x 文件为起始页 并按 F 键 <WebMethod ( ) >Public Function HelloWorld ( ) As String HelloWorld = Hello World End FunctionEnd Class

下面就来介绍Visual Basic Net中使用这个Web Service提供的服务来更新数据库的实现方法

五 在Visual Basic Net调用Web Service提供的服务:

当Web Service已经处于对外提供服务状态 Visual Basic Net就可以通过HTTP 调用 来使用这些服务了 当然前提是要了解Web Service对外提供服务所对应的URL 当了解到Web Service对应的URL后 Visual Basic Net就像是使用本地的类库一样使用Web Service中提供的各种功能 所以有些人说 Web Service从实质上说 就是通过HTTP调用远程组件的一种方式 在Visual Basic Net具体实现加入Web Service可参阅下面步骤中的第七步

在下面介绍的这个数据库应用程序是通过使用上面的Web Service中提供的 Binding 服务 对程序中DataGrid组件实现数据绑定 提供使用Web Service中提供的 Update 服务 通过程序中的DataGrid来修改数据库 下面就是Visual Basic Net中使用Web Service提供服务来编写数据库应用程序的具体步骤 :

启动Visual Studio Net

选择菜单【文件】|【新建】|【项目】后 d出【新建项目】对话框

将【项目类型】设置为【Visual Basic项目】

将【模板】设置为【Windows应用程序】

在【名称】文本框中输入【TestWebService】

在【位置】的文本框中输入【E:\VS NET项目】 然后单击【确定】按钮 这样在 E:\VS NET项目 中就产生了名称为 TestWebService 文件夹 里面存放的就是TestWebService项目的所有文件

选择【解决方案资源管理器】|【引用】后 单击鼠标右键 在d出的菜单中选择【添加Web 引用】 在d出的【添加Web引用】对话框中的【地址】文本框中输入 后 单击回车键后 可得图 所示界面 单击图 中【添加引用】按钮 则在【TestWebService】项目中加入了Web引用 请注意 就是上面完成的Web Service对外提供服务的URL地址 具体可参阅图 所示:

图 :在【TestWebService】添加Web Service提供的服务

从【工具箱】中的【Windows窗体组件】选项卡中往Form 窗体中拖入下列组件 并执行相应的 *** 作:

一个DataGrid组件

二个Button组件 分别是Button 至Button 并在这二个Button组件拖入Form 的设计窗体后 分别双击它们 则系统会在Form vb文件分别产生这二个组件的Click事件对应的处理代码

按照表 所示调整窗体中各组件属性的数值

组件类型 组件名称 属性 设置结果 Form Form Text 测试Web Service Form MaximizeBox False Form FormBorderStyle FixedSingle Button Button Text 绑定 Button FlatStyle Flat Button Text 修改 Button FlatStyle Flat  

表 :【TestWebService】项目中组件的主要属性及其对应数值

在调整完组件属性值后 再按照图 所示调整组件的位置和排列顺序:

图 :【TestWebService】项目中组件排列位置和顺序

把Visual Studio Net的当前窗口切换到Form vb的代码编辑窗口 并用下列代码替换Form vb中的Button 的Click事件对应的处理代码 下列代码功能是使用Web Service中提供的 Binding 服务对DataGrid组件实现数据绑定:

Private Sub Button _Click ( ByVal sender As System Object ByVal e As System EventArgs ) Handles Button Click Dim MyService As New localhost Service ( ) DataGrid DataSource = MyService Binding ( ) DataGrid DataMember = Cust End Sub

用下列代码替换Form vb中的Button 的Click事件对应的处理代码 下列代码功能是使用Web Service中提供的 Update 服务实现通过DataGrid来修改数据库数据:

Private Sub Button _Click ( ByVal sender As System Object ByVal e As System EventArgs ) Handles Button Click Dim MyService As New localhost Service ( ) Dim ds As DataSet = DataGrid DataSource Dim dsChanges As DataSet = ds GetChanges ( ) If Not ( dsChanges Is Nothing ) Thends Merge ( MyService Update ( dsChanges ) True ) End IfEnd Sub

至此 【TestWebService】项目的全部工作就完成了 调用Web Service是不是很简单 此时单击快捷键F 运行程序后 单击程序中的【绑定】按钮就会对程序中的DataGrid组件实现数据绑定 单击程序中的【修改】按钮 则程序会根据DataGrid中的内容来更新数据库 图 就是【TestWebService】的运行界面:

图 :【TestWebService】的运行界面

Form vb的代码清单如下:

Public Class Form Inherits System Windows Forms Form#Region Windows 窗体设计器生成的代码 Public Sub New ( ) MyBase New ( )  该调用是 Windows 窗体设计器所必需的  InitializeComponent ( )  在 InitializeComponent ( ) 调用之后添加任何初始化End Sub 窗体重写处置以清理组件列表 Protected Overloads Overrides Sub Dispose ( ByVal disposing As Boolean ) If disposing ThenIf Not ( ponents Is Nothing ) Then ponents Dispose ( )End If End If MyBase Dispose ( disposing )End Sub Windows 窗体设计器所必需的Private ponents As System ComponentModel IContainer  注意 以下过程是 Windows 窗体设计器所必需的  可以使用 Windows 窗体设计器修改此过程   不要使用代码编辑器修改它  Friend WithEvents Button As System Windows Forms Button Friend WithEvents Button As System Windows Forms Button Friend WithEvents DataGrid As System Windows Forms DataGrid <System Diagnostics DebuggerStepThrough ( ) >Private Sub InitializeComponent ( ) Me Button = New System Windows Forms Button ( ) Me Button = New System Windows Forms Button ( ) Me DataGrid = New System Windows Forms DataGrid ( ) CType ( Me DataGrid System ComponentModel ISupportInitialize ) BeginInit ( ) Me SuspendLayout ( ) Me Button FlatStyle = System Windows Forms FlatStyle Flat Me Button Location = New System Drawing Point ( ) Me Button Name = Button  Me Button Size = New System Drawing Size ( ) Me Button TabIndex =  Me Button Text = 绑定  Me Button FlatStyle = System Windows Forms FlatStyle Flat Me Button Location = New System Drawing Point ( ) Me Button Name = Button  Me Button Size = New System Drawing Size ( ) Me Button TabIndex =  Me Button Text = 修改  Me DataGrid DataMember =  Me DataGrid Dock = System Windows Forms DockStyle Top Me DataGrid HeaderForeColor = System Drawing SystemColors ControlText Me DataGrid Name = DataGrid  Me DataGrid Size = New System Drawing Size ( ) Me DataGrid TabIndex =  Me AutoScaleBaseSize = New System Drawing Size ( ) Me ClientSize = New System Drawing Size ( ) Me Controls AddRange ( New System Windows Forms Control ( ) {Me DataGrid Me Button Me Button } ) Me Name = Form  Me Text = 测试Web Service  CType ( Me DataGrid System ComponentModel ISupportInitialize ) EndInit ( ) Me ResumeLayout ( False )End Sub#End RegionPrivate Sub Button _Click ( ByVal sender As System Object ByVal e As System EventArgs ) Handles Button Click Dim MyService As New localhost Service ( ) DataGrid DataSource = MyService Binding ( ) DataGrid DataMember = Cust End SubPrivate Sub Button _Click ( ByVal sender As System Object ByVal e As System EventArgs ) Handles Button Click Dim MyService As New localhost Service ( ) Dim ds As DataSet = DataGrid DataSource Dim dsChanges As DataSet = ds GetChanges ( ) If Not ( dsChanges Is Nothing ) Thends Merge ( MyService Update ( dsChanges ) True ) End IfEnd SubEnd Class

六 总结

lishixinzhi/Article/program/net/201311/11839

C#学习到一定程度会涉及到C#创建WebService的一些高阶知识,本文试图对此做一个简单的介绍。

假设A是客户端,B是webservice服务端,用户通过http协议向服务器发送soap请求,webservice返回客户端Xml格式的数据。

现在我们看一看创建一个C#创建WebService的大致过程:

服务端的webservice是必须要建的。中间的soap,Xml我们不用去关心,在客户端这边,比较重要的是如何从webservice取得对象?答案是用的是proxy对象。客户端由代理对象(proxy)负责与webservice的通信。所以在客户端使用webservice,完全和使用一个本地对象是一样的。

我们现在以一个简单的C#创建WebService实例来说明。

打开vs.Net,新建工程(asp.Net web服务),在位置中键入http。//localhost/webserver,其中webserver就是工程的名字。确定后,出现一个Service1.asmx.cx,双击,出现代码窗口,

using System using System.Collections using System.ComponentModel using System.Data using System.Diagnostics using System.Web using System.Web.Services namespace webserver { /// /// Service1 的摘要说明。 /// (1) public class Service1 :System.Web.Services.WebService { public Service1() { //CODEGEN:该调用是 ASP.Net Web服务设计器所必需的 InitializeComponent() } #region Component Designer generated code //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" // } } } 下面在(1)处加入

[WebService(Namespace="http。//localhost/webserver/")]

这是因为soap是基于http协议上的,客户端无法知道webservice位于那个服务器上。在实际应用中,比如http。//www。ourfly。com上放置这个webservice,则Namespace改为http。//www。ourfly。com/webserver.

下面我们给这个webservice添加一个方法。

// [WebMethod] // public string HelloWorld() // { // return "Hello World" // } 微软帮我们写好了一个,接着添加一个方法。 方法名称叫show. [WebMethod] public string show(string yourname) { return “http。//www。ourfly。com”+”欢迎”+yourname } 现在,就可以运行了,按F5,点击show,输入你的名字, 然后点击invote 看到了吧。 〈 ?Xml version="1.0" encoding="utf-8" ?〉 〈 string Xmlns="http。//tempuri。org/"〉 http。//www。ourfly。com欢迎g〈 /string〉 成功了。打开bin目录,Vs.Net已经将proxy做好了.webserver.dll.

现在我们在不同的环境下测试:

1.打开vs.Net,新建”windows应用程序”工程,命名为Client,增加按钮,文本框。

现在要用到代理了,右键单击右边的reference(引用),选择”添加引用”,选择浏览,找到webserver目录下的bin目录下的webserver.dll

再加入一个system.web.webservices的引用,在列表中有。

在form1.cs里,加入

using System.Web.Services

using webserver

然后在

private System.Windows.Forms.Button button1

private System.Windows.Forms.TextBox textBox1

后面,插入

private webserver.service1 Client

建立一个service1的实例。双击按钮,代码如下:

private void button1_Click (object sender, System.EventArgs e) { Client =new Service1() string name name=Client.show("龙卷风.Net") textBox1.Text=name } 按F5,运行工程,点击按钮,文本框中显示 http。//www。ourfly。com欢迎龙卷风.Net

2. Asp.Net web窗口的测试

方法与上面的一模一样,添加引用,建立service1的实例 在此不在细说。

3.在VB中测试

这个就要相对来说复杂一些 ,首先在VB中建立一个”标准EXE”的工程。添加引用:Microsoft Soap Type library。

注意:如果没有安装Microsoft Soap Toolkit,是没有这个类型库的。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11405018.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存