<%@ WebService Language="C#" Class="MyMath" %> using System.Web.Services; public class MyMath { [ WebMethod ] public int Add(int num1, int num2) { return num1+num2; } } 声明一个XML Web服务,这个服务的实现存在于一个汇编文件中。
下面的代码示例设置XML域名空间为http://www.contoso.com/。 [C#] <%@ WebService Language="C#" Class="Math" Debug=true%> using System.Web.Services; using System;
[WebService(Namespace="http://www.contoso.com/")] public class Math { [ WebMethod ] public int Add(int num1, int num2) { return num1+num2; } } [Visual Basic] <%@ WebService Language="VB" Class="Math"%> Imports System.Web.Services Imports System
<WebService(Namespace:="http://www.contoso.com/")> _ Public Class Math <WebMethod()> Public Function Add(num1 As Integer, num2 As Integer) As Integer Return num1 + num2 End Function End Class
下面的代码示例使用Context属性来获得服务器上的请求时间。 [C#] <%@ WebService Language="C#" Class="Util" %> using System; using System.Web.Services;
public class Util: WebService { [ WebMethod(Description="Returns the time as stored on the Server",EnableSession=false)] public string Time() { return Context.Timestamp.TimeOfDay.ToString(); } } [Visual Basic] <%@ WebService Language="VB" Class="Util" %> Imports System Imports System.Web.Services
Public Class Util Inherits WebService
<WebMethod(Description := "Returns the time as stored on the Server", _ EnableSession := False)> _ Public Function Time() As String Return Context.Timestamp.TimeOfDay.ToString() End Function End Class
下面的代码示例有两个公共方法,其一是一个XML Web服务方法。Multiply方法是一个XML Web服务方法,因为它有一个应用到它上的WebMethod属性。 [C#] <%@ WebService Language="C#" Class="Util" %> using System; using System.Web.Services; public class Util: WebService { public int Add(int a, int b) { return a + b; }
[ WebMethod] public long Multiply(int a, int b) { return a * b; } } [Visual Basic] <%@ WebService Language="VB" Class="Util" %> Imports System Imports System.Web.Services Public Class Util Inherits WebService
Public Function Add(a As Integer, b As Integer) As Integer Return a + b End Function
< WebMethod()> _ Public Function Multiply(a As Integer, b As Integer) As Long Return a * b End Function End Class