ตัวอย่าง Web Service


การเขียน Web service โดยทำการเรียกใช้แบบ Web และ App.

ตัวอย่าง Code Web service :

FirstService.asmx
  <%@ WebService language="C" class="FirstService" %>

  using System;
  using System.Web.Services;
  using System.Xml.Serialization;

  [WebService(Namespace="http://localhost/MyWebServices/")]
  public class FirstService : WebService
  {
      [WebMethod]
      public int Add(int a, int b)
      {
          return a + b;
      }

      [WebMethod]
      public String SayHello()
      {
          return "Hello World";
      }
  }

วิธีการทดสอบ Web service :

http://localhost/MyWebServices/FirstService.asmx


ตัวอย่าง Web ที่ทำการเรียกใช้ Web service :

WebApp.axpx
  <%@ Page Language="C#" %>
  <script runat="server">
  void runSrvice_Click(Object sender, EventArgs e)
  {
      FirstService mySvc = new FirstService();
      Label1.Text = mySvc.SayHello();
      Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),
                    Int32.Parse(txtNum2.Text)).ToString();
  }
  </script>
  <html>
  <head>
  </head>
  <body>
  <form runat="server">
    <p>
        <em>First Number to Add </em>:
        <asp:TextBox id="txtNum1" runat="server"
             Width="43px">4</asp:TextBox>
    </p>
    <p>
        <em>Second Number To Add </em>:
        <asp:TextBox id="txtNum2" runat="server"
             Width="44px">5</asp:TextBox>
    </p>
    <p>
        <strong><u>Web Service Result -</u></strong>
    </p>
    <p>
        <em>Hello world Service</em> :
        <asp:Label id="Label1" runat="server"
             Font-Underline="True">Label</asp:Label>
    </p>
    <p>
        <em>Add Service</em> :
        & <asp:Label id="Label2" runat="server"
               Font-Underline="True">Label</asp:Label>
    </p>
    <p align="left">
        <asp:Button id="runSrvice" onclick="runSrvice_Click"
             runat="server" Text="Execute"></asp:Button>
    </p>
  </form>
  </body>
  </html>

ตัวอย่าง App. ที่ทำการเรียกใช้ Web service :

WinApp.cs
  using System;
  using System.IO;

  namespace SvcConsumer{
  class SvcEater
  {
      public static void Main(String[] args)
      {
          FirstService mySvc = new FirstService();

          Console.WriteLine("Calling Hello World Service: " +
                             mySvc.SayHello());
          Console.WriteLine("Calling Add(2, 3) Service: " +
                             mySvc.Add(2, 3).ToString());
      }
  }
  }

คำสำคัญ (Tags): #web service#soap#xml
หมายเลขบันทึก: 127111เขียนเมื่อ 11 กันยายน 2007 15:52 น. ()แก้ไขเมื่อ 24 มิถุนายน 2012 00:35 น. ()สัญญาอนุญาต: จำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (0)

ไม่มีความเห็น

พบปัญหาการใช้งานกรุณาแจ้ง LINE ID @gotoknow
ClassStart
ระบบจัดการการเรียนการสอนผ่านอินเทอร์เน็ต
ทั้งเว็บทั้งแอปใช้งานฟรี
ClassStart Books
โครงการหนังสือจากคลาสสตาร์ท