C#调用WebService

摘录:

二、Web Service开发

.net平台内建了对Web Service的支持,包括Web Service的构建和使用。与其它开发平台不同,使用.net平台,你不需要其他的工具或者SDK就可以完成Web Service的开发了。.net Framework本身就全面支持Web Service,包括服务器端的请求处理器和对客户端发送和接受SOAP消息的支持。下来我们就一步一步的用Microsoft Visual Studio .net 20058(后面简称VS.Net 2008)创建和使用一个简单的Web Service。

2.1、用创建一个最简单的Web Service

首先,打开VS2005,打开"文件-新建-网站",选择"ASP.NET Web服务"

 

查看Service.cs代码,你会发现VS.Net 2005已经为Web Service文件建立了缺省的框架。原始代码为:

view plaincopy to clipboardprint?
using System;   
using System.Linq;   
using System.Web;   
using System.Web.Services;   
using System.Web.Services.Protocols;   
using System.Xml.Linq;   
[WebService(Namespace = "http://tempuri.org/")]   
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]   
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。   
// [System.Web.Script.Services.ScriptService]   
public class Service : System.Web.Services.WebService   
{   
    public Service () {   
        //如果使用设计的组件,请取消注释以下行    
        //InitializeComponent();    
    }   
    [WebMethod]   
    public string HelloWorld()   
    {   
        return "Hello World";   
    }   
}  
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service () {
        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

默认工程里面已经有一个Hello World的方法了,直接运行看看效果,

 

点击显示页面上图中的"HelloWorld"超链接,跳转到下一页面:

 

点击"调用"按钮,就可以看到用XML格式返回的Web Service结果下图。说明我们的Web Service环境没有问题,而且还初步接触了一下最简单的Web Service。

2.2、创建一个简单带有功能的Web Service

上面我们宏观的了解了webservice,其实它就是个对外的接口,里面有函数可供外部客户调用(注意:里面同样有客户不可调用的函数).假若我们是服务端,我们写好了个webservice,然后把它给了客户(同时我们给了他们调用规则),客户就可以在从服务端获取信息时处于一个相对透明的状态.即是客户不了解(也不需要)其过程,他们只获取数据.在代码文件里,如果我们写了一个函数后,希望此函数成为外部可调用的接口函数,我们必须在函数上面添上一行代码[WebMethod(Description="函数的描述信息")],如果你的函数没有这个申明,它将不能被用户引用.下来我们开始编写一个简单的Web Service 的例子。

先把默认的HelloWorld方法注释掉,简单的写了求加减乘除运算的四个方法;

view plaincopy to clipboardprint?
using System;   
using System.Linq;   
using System.Web;   
using System.Web.Services;   
using System.Web.Services.Protocols;   
using System.Xml.Linq;   
[WebService(Namespace = "http://tempuri.org/")]   
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]   
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。   
// [System.Web.Script.Services.ScriptService]   
public class Service : System.Web.Services.WebService   
{   
    public Service () {   
        //如果使用设计的组件,请取消注释以下行    
        //InitializeComponent();    
    }   
    //[WebMethod]   
    //public string HelloWorld()   
    //{   
    //    return "Hello World";   
    //}   
    [WebMethod(Description = "求和的方法")]   
    public double addition(double i, double j)   
    {   
        return i + j;   
    }   
    [WebMethod(Description = "求差的方法")]   
    public double subtract(double i, double j)   
    {   
        return i - j;   
    }   
    [WebMethod(Description = "求积的方法")]   
    public double multiplication(double i, double j)   
    {   
        return i * j;   
    }   
    [WebMethod(Description = "求商的方法")]   
    public double division(double i, double j)   
    {   
        if (j != 0)   
            return i / j;   
        else  
            return 0;   
    }   
}  
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service () {
        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }
    //[WebMethod]
    //public string HelloWorld()
    //{
    //    return "Hello World";
    //}
    [WebMethod(Description = "求和的方法")]
    public double addition(double i, double j)
    {
        return i + j;
    }
    [WebMethod(Description = "求差的方法")]
    public double subtract(double i, double j)
    {
        return i - j;
    }
    [WebMethod(Description = "求积的方法")]
    public double multiplication(double i, double j)
    {
        return i * j;
    }
    [WebMethod(Description = "求商的方法")]
    public double division(double i, double j)
    {
        if (j != 0)
            return i / j;
        else
            return 0;
    }
}
 

运行可以看到我们自己写的可以被调用的方法,如下图:

 

同样点击addition方法,进入addition方法的调用页。

 

在参数上面输入参数i=3,j=3,如上图,点击调用,就可以看到用XML格式返回的Web Service结果(i与j相加的结果)下图

 到这里,我们会发现,其实webservice并不是那么的神秘,它也不过只是个接口,对我们而言,侧重点就是是接口函数的编写.

2.3、用ASP.NET调用Web Service
首先,打开VS2005,打开"文件-新建-网站",选择"ASP.NET网站"。

 

选好存储位置,语言后点击确定,进入默认页面。然后先添加Web引用,把WebService引到当前的工程里面。方法是:在资源管理器中点击右键,选择添加Web 引用,调出对话框:

(此处同时要使服务处于运行中)

 

在URL中填入,前面写好的WebService运行后浏览器上面显示的地址(即:WebService发布后的访问地址 ),点击"前往"按钮,如上图,就会显示出所引用的WebService中可以调用的方法,然后点击"添加引用",就将webservice引用到了当前的工程里面 ,如下图,解决方案中会出现引进来的WebService文件

 

我们在这就练习调用webservice的四个方法,做一个简单的调用的例子,先在网站的前台添加几个控件,代码如下:

view plaincopy to clipboardprint?
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml">   
<head runat="server">   
    <title>无标题页</title>   
</head>   
<body>   
    <form id="form1" runat="server">   
    <div>   
        <asp:TextBox ID="Num1" runat="server"></asp:TextBox>   
             <select id="selectOper" runat = "server">   
                 <option>+</option>   
                 <option>-</option>   
                 <option>*</option>   
                 <option>/</option>   
             </select>   
             <asp:TextBox ID="Num2" runat="server"></asp:TextBox>   
        <asp:Button ID="Button1" runat="server" Text="=" onclick="Button1_Click" />   
             <asp:TextBox ID="Result" runat="server"></asp:TextBox>   
    </div>   
    </form>   
</body>   
</html>  
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="Num1" runat="server"></asp:TextBox>
             <select id="selectOper" runat = "server">
                 <option>+</option>
                 <option>-</option>
                 <option>*</option>
                 <option>/</option>
             </select>
             <asp:TextBox ID="Num2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="=" onclick="Button1_Click" />
             <asp:TextBox ID="Result" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>
 

然后在后台写调用的代码,调用之前和使用其它的对象一样,要先实例化,实例化的方法是localhost.Service a = new localhost.Service();然后就可以通过a来访问WebService里面提供的方法了。在这个例子里面,动态的创建了一个button控件来触发WebService的调用,后台代码如下:
运行后可以看到效果,如下图所示,在前面两个Textbox里面输入两个操作数,在中间的下拉列表中选择操作符,然后点击"="号,将计算的结果输出到第三个Textbox里面。

 

而整个计算并不是在本地进行的,是在Web服务端进行计算的然后将结果通过XML返还给了调用方的,所以,在运行该程序的时候,WebService程序还必须启动,否则会报无法连接远程服务器的异常,如下图:

 

后台代码如下:

view plaincopy to clipboardprint?
using System;   
using System.Configuration;   
using System.Data;   
using System.Linq;   
using System.Web;   
using System.Web.Security;   
using System.Web.UI;   
using System.Web.UI.HtmlControls;   
using System.Web.UI.WebControls;   
using System.Web.UI.WebControls.WebParts;   
using System.Xml.Linq;   
public partial class _Default : System.Web.UI.Page    
{   
    protected void Page_Load(object sender, EventArgs e)   
    {   
    }   
    protected void Button1_Click(object sender, EventArgs e)   
    {   
        string selectFlag = selectOper.Value;   
        localhost.Service web = new localhost.Service();   
        if (selectFlag.Equals("+"))   
        {   
            Result.Text =(web.addition(double.Parse(Num1.Text),double.Parse(Num2.Text))).ToString();   
        }   
        else if (selectFlag.Equals("-"))   
        {   
            Result.Text = (web.subtract(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();   
        }   
        else if (selectFlag.Equals("*"))   
        {   
            Result.Text = (web.multiplication(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();   
        }   
        else if (selectFlag.Equals("/"))   
        {   
            Result.Text = (web.division(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();   
        }   
    }   
}  
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string selectFlag = selectOper.Value;
        localhost.Service web = new localhost.Service();
        if (selectFlag.Equals("+"))
        {
            Result.Text =(web.addition(double.Parse(Num1.Text),double.Parse(Num2.Text))).ToString();
        }
        else if (selectFlag.Equals("-"))
        {
            Result.Text = (web.subtract(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();
        }
        else if (selectFlag.Equals("*"))
        {
            Result.Text = (web.multiplication(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();
        }
        else if (selectFlag.Equals("/"))
        {
            Result.Text = (web.division(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();
        }
    }
}
 

到此一个一个简单的WebService的开发和调用就已经完成了,在实际应用中可以根据自己的需要,写一些功能强大的,复杂的WebService,不管多么复杂,整个流程都是这样的。

转载地址:http://blog.csdn.net/h0322/archive/2009/11/07/4776819.aspx


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wl_ldy/archive/2010/05/23/5618626.aspx

 
 
原文地址:https://www.cnblogs.com/ITGirl00/p/3456840.html