ASP.NET - Web服务

Web服务是使用Web应用程序使用的Web协议访问的基于Web的功能. Web服务开发有三个方面:

  • 创建Web服务

  • 创建代理

  • 使用网络服务

创建网络服务

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

为了理解这个概念,让我们创建一个Web服务来提供库存价格信息.客户可以根据股票代码查询股票的名称和价格.为了简化这个例子,这些值是在二维数组中硬编码的.此Web服务有三种方法:

  • 默认的HelloWorld方法

  • 一个GetName方法

  • GetPrice方法

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

步骤(1):选择文件 - >新 - > Visual Studio中的Web站点,然后选择ASP.NET Web Service.

步骤(2):一个名为Service.asmx的Web服务文件及其后面的代码文件,Service.cs在项目的App_Code目录中创建.

步骤(3):将文件名更改为StockService.asmx和StockService .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):点击方法名称,检查它是否正常运行.

获取名称

步骤(9):为了测试GetName方法,提供其中一个硬编码的股票代码,它返回股票名称

股票名称

使用Web服务

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

Web应用程序的内容文件如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="wsclient._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>
         Untitled Page
      </title>
   </head>
   
   <body>
   
      <form id="form1" runat="server">
         <div>
         
            <h3>Using the Stock Service</h3>
            
            <br /> <br />
            
            <asp:Label ID="lblmessage" runat="server"></asp:Label>
            
            <br /> <br />
            
            <asp:Button ID="btnpostback" runat="server" onclick="Button1_Click" Text="Post Back" style="width:132px" />
               
            <asp:Button ID="btnservice" runat="server" onclick="btnservice_Click"  Text="Get Stock" style="width:99px" />
            
         </div>
      </form>
      
   </body>
</html>

Web应用程序的代码隐藏文件如下:

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;

namespace wsclient
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            lblmessage.Text = "First Loading Time: " +  DateTime.Now.ToLongTimeString
         }
         else
         {
            lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString();
         }
      }
      
      protected void btnservice_Click(object sender, EventArgs e)
      {
         StockService proxy = new StockService();
         lblmessage.Text = String.Format("Current SATYAM Price:{0}",
         proxy.GetPrice("SATYAM").ToString());
      }
   }
}

创建代理

代理是Web服务代码的替身.在使用Web服务之前,必须创建代理.代理已在客户端应用程序中注册.然后客户端应用程序使用本地方法调用Web服务.

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

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

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

protected void btnservice_Click(object sender, EventArgs e)
{
   StockService proxy = new StockService();
   lblmessage.Text = String.Format("Current SATYAM Price: {0}", 
   proxy.GetPrice("SATYAM").ToString());
}

按照以下步骤创建代理:

步骤(1) :右键单击Solution Explorer中的Web应用程序条目,然后单击"Add Web Reference".

添加Web引用

步骤(2):选择"此解决方案中的Web服务".它返回StockService引用.

选择Web服务

步骤(3):单击该服务将打开测试网页.默认情况下,创建的代理称为"localhost",您可以重命名它.单击"添加引用"将代理添加到客户端应用程序.

Stock Service 2

通过添加以下代码将代理包含在代码隐藏文件中:

 
 using localhost;