ASP.NET基础 专题
您的位置:csharp > ASP.NET基础专题 > ASP.NET Web Services
ASP.NET Web Services
作者:--    发布时间:2019-11-20

web服务是一种基于web的功能,可以使用web应用程序使用的web协议进行访问。web服务开发有三个方面:

  • 创建web服务
  • 创建一个代理
  • 使用web服务

创建一个web服务

web服务是一个web应用程序,它基本上是由其他应用程序可以使用的方法组成的类。它也遵循一个代码隐藏的体系结构,如asp.net网页,尽管它没有用户界面。

为了理解这个概念,创建一个web服务来提供股票价格信息。客户可以根据股票代码查询股票的名称和价格。 为了保持这个例子简单,股票的信息被硬编码在一个二维数组中。 这个web服务有三种方法:

  • 默认的helloworld方法
  • getname方法用于获取股票的名称
  • getprice方法用于获取股票的价格

按照以下步骤创建web服务:

第1步: 在visual studio中选择菜单:文件 -> 新建 -> 网站,然后选择asp.net空网站,输入项目名称为:webservices

第2步: 在项目上右击选择“添加新建项目” ->web -> web服务。在项目的app_code目录中创建名为service.asmx的web服务文件及其代码,文件service.cs

第3步: 将上面两个文件的名称更改为stockservice.asmxstockservice.cs

第4步: .asmx文件只有一个webservice指令:

<%@ webservice language="c#" codebehind="~/app_code/stockservice.cs" class="stockservice" %>

第5步: 打开stockservice.cs文件,其中生成的代码是基本的hello world服务。 默认的web服务代码隐藏文件如下所示:

using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.linq;

using system.web;
using system.web.services;
using system.web.services.protocols;

using system.xml.linq;

namespace stockservice
{
   // <summary>
   // summary description for service1
   // <summary>

   [webservice(namespace = "http://tempuri.org/")]
   [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
   [toolboxitem(false)]

   // to allow this web service to be called from script, 
   // using asp.net ajax, uncomment the following line. 
   // [system.web.script.services.scriptservice]

   public class service1 : system.web.services.webservice
   {
      [webmethod]

      public string helloworld()
      {
         return "hello world";
      }
   }
}

第6步: 更改文件后面的代码,为股票代码,名称和价格添加字符串的二维数组,获取股票信息。

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)]

// to allow this web service to be called from script, 
// using asp.net ajax, uncomment the following line. 
// [system.web.script.services.scriptservice]

public class stockservice : system.web.services.webservice
{
    public stockservice()
    {
        //uncomment the following if using designed components 
        //initializecomponent(); 
    }

    string[,] stocks =
    {
      {"relind", "reliance industries", "1060.15"},
      {"icici", "icici bank", "911.55"},
      {"jsw", "jsw steel", "1201.25"},
      {"wipro", "wipro limited", "1194.65"},
      {"satyam", "satyam computers", "91.10"}
   };

    [webmethod]
    public string helloworld()
    {
        return "hello world";
    }

    [webmethod]
    public double getprice(string symbol)
    {
        //it takes the symbol as parameter and returns price
        for (int i = 0; i < stocks.getlength(0); i++)
        {
            if (string.compare(symbol, stocks[i, 0], true) == 0)
                return convert.todouble(stocks[i, 2]);
        }

        return 0;
    }

    [webmethod]
    public string getname(string symbol)
    {
        // it takes the symbol as parameter and 
        // returns name of the stock
        for (int i = 0; i < stocks.getlength(0); i++)
        {
            if (string.compare(symbol, stocks[i, 0], true) == 0)
                return stocks[i, 1];
        }

        return "stock not found";
    }
}

第7步: 运行web服务应用程序给出web服务测试页面,其允许测试服务方法。如下图所示 -

第8步: 点击方法名称,检查是否正常运行。例如,点击:getname 方法 -

第9步: 要测试getname方法,提供一个股票代码(这里输入:jsw并点击调用),它是硬编码的,它返回股票的名称 -

使用web服务

要使用web服务,请在同一解决方案下创建一个web站点,名称为:webservicecall 。 这可以通过右键单击解决方案资源管理器中的解决方案名称来完成。 调用web服务的网页应该有一个标签控件来显示返回的结果和一个用于调用服务的按钮。

web应用程序(default.aspx)的内容文件如下所示:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>webservices调用示例</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <h3>使用股票web服务的示例</h3>

            <br /> <br />

            <asp:label id="lblmessage" runat="server"></asp:label>

            <br /> <br />
            <asp:button id="btnservice" runat="server" onclick="btnservice_click"  text="获得股票信息" style="width:99px" />

         </div>
    </form>
</body>
</html>

web应用程序的文件(default.aspx.cs)的后端代码如下所示:

using system;
using system;
using system.collections;
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;

//this is the proxy
using localhost;


public partial class _default : system.web.ui.page
{

    protected void page_load(object sender, eventargs e)
    {
        if (!ispostback)
        {
            lblmessage.text = "第一次加载时间: " + datetime.now.tolongtimestring();
         }
        else
        {
            lblmessage.text = "回传时间: " + datetime.now.tolongtimestring();
        }
    }

    protected void btnservice_click(object sender, eventargs e)
    {
        stockservice proxy = new stockservice();
        lblmessage.text = string.format("当前satyam股票的价格:{0}",
        proxy.getprice("satyam").tostring());
    }
}

创建代理

代理是web服务代码的替代品。在使用web服务之前,必须创建代理。 代理向客户端应用程序注册。然后,客户端应用程序使用本地方法调用web服务。

代理接受调用,以适当的格式包装它,并将其作为soap请求发送到服务器。soap代表简单对象访问协议。该协议用于交换web服务数据。

当服务器将soap包返回给客户端时,代理解码所有内容并将其呈现给客户端应用程序。

在使用btnservice_click调用web服务之前,应该将web引用添加到应用程序中。 这会透明地创建一个代理类,由btnservice_click事件使用。

按照以下步骤创建代理:

第1步: 右键单击解决方案资源管理器中的web应用程序条目,然后单击添加服务引用,然后选择高级

第2步: 选择“此解决方案中的web服务”。它返回stockservice 引用。

第3步: 点击服务打开测试网页。 默认情况下,创建的代理名称为localhost,也可以重命名它。点击“添加引用”将代理添加到客户端应用程序。

在代码后面的代码中加入代理,方法是:

using localhost;

运行webservicecall 项目,得到以下结果 -

点击获取股票价格 按钮,得到以下结果 -


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册