1、Web服务代码:
1: using System.Web.Services;
2: using System.Web.Services.Protocols;
3:
4: /// <summary>
5: /// Summary description for QuotesService
6: /// </summary>
7: [WebService(Namespace = "http://tempuri.org/")]
8: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
9: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
10: // [System.Web.Script.Services.ScriptService]
11: public class QuotesService : System.Web.Services.WebService
12: {
13:
14: public QuotesService()
15: {
16:
17: //Uncomment the following line if using designed components
18: //InitializeComponent();
19: }
20:
21: [WebMethod(Description = "返回给定股票的实时报价")]
22: public double GetStockPrice(string symbol)
23: {
24: double price = 0;
25: switch (symbol.ToUpper())
26: {
27: case "INTC":
28: price = 70.75;
29: break;
30: case "MSFT":
31: price = 50;
32: break;
33: case "DELL":
34: price = 42.25;
35: break;
36: default:
37: throw new SoapException("无效的字符串", SoapException.ClientFaultCode, "http://www.cvh.org.cn/GetStockPrice");
38: }
39: return price;
40:
41: }
42: }
43:
2、页面代码:
1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4:
5: <html xmlns="http://www.w3.org/1999/xhtml">
6: <head runat="server">
7: <title></title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: 请输入股票代码:
13: <asp:TextBox ID="txtSymbol" runat="server"></asp:TextBox>
14: <asp:Button ID="btnGetQuote" Text="Get Quote" runat="server" onclick="btnGetQuote_Click" />
15: <br /><br /><br />
16: <asp:Label ID="lblMessage" Font-Bold="true" runat="server"></asp:Label>
17:
18: </div>
19: </form>
20: </body>
3、执行代码:
1: using System;
2: using System.Web.Services.Protocols;
3:
4:
5: public partial class Default2 : System.Web.UI.Page
6: {
7: protected void Page_Load(object sender, EventArgs e)
8: {
9:
10: }
11: protected void btnGetQuote_Click(object sender, EventArgs e)
12: {
13: try
14: {
15: QuotesProxy.QuotesService obj = new QuotesProxy.QuotesService();
16: lblMessage.Text = obj.GetStockPrice(txtSymbol.Text).ToString();
17: }
18: catch (SoapException soapEx)
19: {
20: lblMessage.Text = "Actor: " + soapEx.Actor + "<br><br>";
21: lblMessage.Text += "Code: " + soapEx.Code + "<br><br>";
22: lblMessage.Text += "Message: " + soapEx.Message + "<br><br>";
23: lblMessage.Text += "Node: " + soapEx.Node + "<br><br>";
24:
25: }
26: catch (Exception ex)
27: {
28: lblMessage.Text = "抛出的异常是:" + ex.Message;
29: }
30: }
31: }
4、执行结果:
5、使用SoapExcetion的有点如下: