Przykłady Web Services

Każda aplikacja może mieć komponent Web Service.

Tworzenie i programowanie Web Services nie zależy od rodzaju języka programowania.

Przykład: ASP.NET Web Service

W tym przykładzie użyjemy ASP.NET do stworzenia prostego Web Service.

<%@ WebService Language="VB" Class="TempConvert" %>
Imports System
Imports System.Web.Services
Public Class TempConvert : Inherits WebService
<WebMethod()> Public Function FahrenheitToCelsius
(ByVal Fahrenheit As Int16) As Int16
	Dim celsius As Int16 
	celsius = ((((Fahrenheit) - 32) / 9) * 5) 
	Return celsius
End Function
<WebMethod()> Public Function CelsiusToFahrenheit
(ByVal Celsius As Int16) As Int16
	Dim fahrenheit As Int16
	fahrenheit = ((((Celsius) * 9) / 5) + 32) 
	Return fahrenheit
End Function
End Class

Ten dokument jest plikiem .asmx. To rozszerzenie pliku ASP.NET używane do XML Web Services.

Aby uruchomić ten przykład, potrzebujemy serwera .NET

Pierwsza linia tego dokumentu wskazuje, że jest to Web Service napisany w VB, jego nazwa klasy to "TempConvert".

<%@ WebService Language="VB" Class="TempConvert" %>

Następne linie kodu importują przestrzeń nazw "System.Web.Services" z .NET Framework.

Imports System
Imports System.Web.Services

Poniższa linia definiuje klasę "TempConvert" jako klasę WebSerivce:

Public Class TempConvert : Inherits WebService

Następne kroki to podstawowa programowanie w VB. Ta aplikacja ma dwie funkcje. Jedna konwertuje stopnie Fahrenheita na stopnie Celsjusza, a druga konwertuje stopnie Celsjusza na stopnie Fahrenheita.

Jedyną różnicą w porównaniu do zwykłych aplikacji jest to, że ta funkcja jest zdefiniowana jako "WebMethod".

Proszę użyć "WebMethod" do oznaczenia funkcji w aplikacji, która ma być web services.

<WebMethod()> Public Function FahrenheitToCelsius
(ByVal Fahrenheit As Int16) As Int16
	Dim celsius As Int16 
	celsius = ((((Fahrenheit) - 32) / 9) * 5) 
	Return celsius
End Function
<WebMethod()> Public Function CelsiusToFahrenheit
(ByVal Celsius As Int16) As Int16
	Dim fahrenheit As Int16
	fahrenheit = ((((Celsius) * 9) / 5) + 32) 
	Return fahrenheit
End Function

Ostatnią rzeczą do zrobienia jest zakończenie funkcji i klasy:

End Function
End Class

Jeśli zapiszesz ten plik jako plik .asmx i opublikujesz go na serwerze obsługującym .NET, będziesz miał pierwszy działający Web Service.

Automatyczne przetwarzanie ASP.NET

Przez ASP.NET nie musisz osobiście pisać dokumentów WSDL i SOAP.

Jeśli dokładnie przeanalizujesz nasz przykład, zauważysz, że ASP.NET automatycznie tworzy WSDL i żądania SOAP.