导航

Web Service

Posted on 2013-12-20 17:36  好好学习 天天向上  阅读(141)  评论(0编辑  收藏  举报

Web Service概述

WebService其实是一种在线服务,其他人可以通过internet访问并使用已经发布的web service.

它的优点

互操作性: 不同的程序以及在不同平台上开发的程序可以互相通信,因为他的通信协议是SOAP

普遍性: 基于标准的互联网标准如XML,HTTP等

易于使用

相关协议

SOAP: 基于XMl         SOAP可以在HTTP上传输,使用HTTP的安全构架

WSDL :XML文档,定义soap消息以及他们之间的交换.

UDDI  : UniversalDiscoveryDescription and Integration.管理web service信息的

Web service的ASP.NET实现

选择asp.net Web服务模板,然后你会看到VS已经自动为我们生成了一个Web Service的示例代码。

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service()
    {

        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

通常一个web Service文件对应的只有一个类,当然并不是说你不可以在一个.asmx文件中写多个类,但只有与WebService指令中的className值对应的那个类才会被公开。而对于类中的方法,我们必须显式加上[WebMthod]特性,才能被公开,这点与类不同。

WebMethod特性的一些其它属性:

属性 功能 示例
BufferResponse 设置为True时,XML Web服务的响应就保存在内存中,并发送为一个完整的包。如果该属性设置为False,则响应在服务器上构造的同时,会发送给客户机。 [WebMethod(BufferResponse=true)]
CacheDuration 指定响应在系统的高速缓存中的保存时间(秒),默认值为0,表示禁用高速缓存。把XML Web服务的响应放在高速缓存中,会提高Web服务的性能。     [WebMethod(BufferResponse=true,CacheDuration=30)]
Description 对在XML Web服务的测试页面上显示的Web Method应用文本的描述。 [WebMethod(Description="该方法用于获取一个简单的字符串")]
EnableSession 设置为True时,会激活Web Method的会话状态,其默认值为False。 [WebMethod(EnableSession=true)]
MessageName 给Method指定一个唯一的名称,如果要使用重载的Web Method,则必须指定。 [WebMethod(MessageName="Method1")]
TransactionOption 为Web Method指定事务的支持,其默认值为Disbled。如果Web Method是启动事务的根对象,Web服务就可以用另一个需要事务处理的WebMethod参与事务处理。其值可以是NotSupported、Supported、Required和RequiresNew。 [WebMethod(TransactionOption=System.EnterpriseServices.TransactionOption.Supported)

 

使用

Web 服务的方法的使用方法同其他引用完全一样,例如

  private void btnRunMtd2_Click(object sender, EventArgs e)
       {
            WebServiceTest.Service1 src = new TestWinApp.WebServiceTest.Service1();
          src.Url = txtAddress.Text;

         string id = this.txtParam1.Text;
           int count = int.Parse ( txtParam2 .Text );
           string user = txtParam3.Text;

           MessageBox.Show("Web Service Return: " + src.TestMtd ( id , count , user ));
       }
当然前提是你要把web service现发布 ,然后再在这里引用它 不然你是new不出来的