ตัวอย่าง 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());
}
}
}
ไม่มีความเห็น