This page has been translated using an automatic translation service and the translation may not be very accurate.

Introduction to the Web Service with NET (English)

If you use this code and feel it is a useful tool, consider making a donation (through PayPal) to help support the project. You can donate as little or as much as you wish, any amount is greatly appreciated!

Italian page For the original Italian page, please click on the link: http://guru4.net/articoli/webservice-introduzione/default.aspx

The Web Service ("Web services" in the Italian translation) are a way to execute calls associated to remote methods through HTTP. In practical draft of usable code from "human" a final customer but also from other programs and the idea is not not only sure new; various techniques for this type of communication exist in fact, like as an example RPC, DCOM and MSMQ.
The limit evidenced from these technologies is that they work alone between analogous systems: MSMQ converses alone with MSMQ, client a single DCOM with a serveur DCOM and therefore via. The Web services have exceeded this limit thanks to SOAP (Simple Object Access Protocol), a protocol based on universal riproducibile XML and therefore, in way of all the independent one from the technological platform prechosen. In particular NET the Framework puts to disposition all how much turns out necessary in order to supply and/or to use Web services.
In the following example we will see like creating a Web service, like testing it and realizing two various applications client that they use the service (consumer).

To create a Web Service

A Web service in NET comes directly exposed inserting code in rows asmx or making reference to the classes of Web services from these rows.
Used the Web service as example is a simple converter Liras/Euro; they will come therefore exposed two methods: conversion from Liras to Euro and conversion from Euro to Liras.
In one virtual folder of IIS (as an example: http://localhost/webservice) we create the rows euroconv.asmx:

<%@ Webservice Language="C#" class="EuroConv"%>

using System;
using System.Web.Services;

[WebService (
    Description = "Web Service per la conversione da Lire ad Euro e da Euro a Lire",
    Namespace = "http://www.guru4.net/EuroConv"
)]

public class EuroConv
{
    [WebMethod(Description="Conversione da Lire a Euro")]
    public double Lire2Euro (int Lire)
    {
        return (Lire / 1936.27);
    }

    [WebMethod(Description="Conversione da Euro a Lire")]
    public int Euro2Lire (double Euro)
    {
        return (int)(Euro * 1936.27);
    }
}

In particular you notice yourself:

  • the Webservice directive that it indicates to NET that the code contained in the class will have to be exposed like Web service

  • the directive using System.Web.Serivice in order to import the namespace that contains the infrastructure code used in the Web Service

  • the modifier [ WebService ] in the declaration of the class that implements the Web Service

  • the modifier [ WebMethod ] in every method that is desired to expose like Web service

To test the service

In NET the Web services they can be uses you from the client simpler that you have to disposition: browser (the Internet advanced Explorer 5,5 or).

To visualize the interface of the service Web

Digitando in the bar of the addresses the URL of our Web Service comes visualized a Web page that documents the interface of the service:

Verification of the Web service through Internet 
Explorer

The Description parameters specify to you in the modifiers of the service and of the methods, they come introduces in the page, improving decidedly the understanding to you of the functionalities of the Web Service.
In case in the code of our service we had not indicated a specific namespace for our service, the aforesaid page would have shown also information adds them approximately the use of the spaces of names in NET and, of default, to our Web Service it would have been automatically assigned like namespace http://tempuri.org; also in absence of a specific namespace the service works correctly (once distributed in Internet, could but generate conflicts with services of other producers!)

Autodescrizione of the Web Service: WSDL

In order to allow I use it of sevizio the Web, is necessary that this supplies the own "description" in rows WSDL (Web Service Description Language).
In this way the utilizzatori will be able to know the methods exposed from the service, the parameters demands, the protocols support to you, etc (one po' like the type library for members COM but with the substantial difference that WSDL has external valence also to the Microsoft world!)
Semantic and the sintassi of rows WSDL is rather complex to generate manually; the platform NET allows but to create in way automatic rifle totally rows WSDL simply recalling the Web service with parameter WSDL, as an example: http://localhost/webservice/euroconv.asmx?WSDL, or, making reference figure 1, cliccando on "description of the service".
The result is following

WSDL of the Web Service

The more important part of rappresentazione WSDL is given from the description of the types of element associates you to the demands and the answers:

<types>
    <s:schema elementFormDefault="qualified" targetNamespace="http://www.guru4.net/EuroConv">
        <s:element name="Lire2Euro">
            <s:complexType>
                <s:sequence>
                    <s:element minOccurs="1" maxOccurs="1" name="Lire" type="s:int" />
                </s:sequence>
            </s:complexType>
        </s:element>
        <s:element name="Lire2EuroResponse">
            <s:complexType>
                <s:sequence>
                    <s:element minOccurs="1" maxOccurs="1" name="Lire2EuroResult" type="s:double" />
                </s:sequence>
            </s:complexType>
        </s:element>
        <s:element name="Euro2Lire">
            <s:complexType>
                <s:sequence>
                    <s:element minOccurs="1" maxOccurs="1" name="Euro" type="s:double" />
                </s:sequence>
            </s:complexType>
        </s:element>
        <s:element name="Euro2LireResponse">
            <s:complexType>
                <s:sequence>
                    <s:element minOccurs="1" maxOccurs="1" name="Euro2LireResult" type="s:int" />
                </s:sequence>
            </s:complexType>
        </s:element>
        <s:element name="double" type="s:double" />
        <s:element name="int" type="s:int" />
    </s:schema>
</types>

The description contains also the descriptions of the types demands from the answers and the demands, beyond to several binding on the service that render the rows rather along.

To verify the operation of the service

In order to directly test the single methods exposed from the Web Service, we can simply make to cliccare the relati ones to you link in figure 1; that is equivalent to recall our service passing to the rows asmx like parameter "?op=[nome of the method ]". It will come visualized a Web page with the description of the method, form for the breaking in of the parameters demands from the method and examples of demand and answer in the protocols it supports (SOAP, GET and POST to you). Sending form (the key "It recalls" or "Invoke" in the English version of NET), we will obtain the answer (using called in GET):

To verify a method of the Web Service

The listener of ASP.NET that indifferently addresses all the demands in arrival to the objects of the Web Service chip ax all and the three methods of pacchettizzazione of data (HTTP GET, HTTP POST and SOAP). The first two have been implement to you in order to guarantee the compatibility with the previous versions in how much use it of SOAP turn out preferibile since remarkablly simplify the communication between the application client and the service. In fact, as we can see in figure 3, the Web Service "answers" in XML: receiving such information via HTTP GET or POST, it remains to cargo of the consumer to extrapolate II data as an example (using parser a XML); instead, using SOAP in atmosphere NET, the consumer it receives the pre-tried demand, therefore ready to the use! We will see in concrete the SOAP advantages realizing a consumer for the serivizio of conversion Euro/Liras.

To create the consumer of the Web service

We create two distinguished applications that use our Web Service: one Web page and a Windows application. In the first case we will use alone the block notes and the SDK of the NET framework, while in according to case we will use Visual Study NET

Client ASP.NET

In order to realize a Web application that uses the Web service we must create one class proxy and one page ASP.NET

The class proxy

Given rows WSDL of the Web service, we can create a class that make from proxy for our page ASP.NET, that is a member that allows us to approach in transparent way the Web Service, without preoccuparci of the modalities with which this comes called and used; the class proxy will put therefore to disposition the service exactly like if she were a member from we realized and used in the plan.
The utility to line of commando wsdl.exe of the SDK of NET class allows us to generate one proxy:

wsdl /language:CS http://localhost/webservice/euroconv.asmx?WSDL

The parameter language allows us to specify goddesses supporati languages dal NET framework (nell' example has been demanded to wsdl.exe generating one class C #).
The result of the aforesaid operation is the generation of the EuroConv.cs rows, containing the code of the class proxy for the EuroConv service:
To this point it does not remain to us that to compile the rows of which over, always using the SDK:

csc /t:library /out:EuroConv.dll EuroConv.cs /r:system.dll /r:system.xml.dll /r:system.web.services.dll

We have that is compiled the class like bookcase of classes (/t:library) indicating like result of the EuroConv.dll compilation and using the metadata one it specifies to you in the parameters /r
To this point the EuroConv.dll rows will have as an example to be inserted in folder /BIN of the application that will use it, http://localhost/consumer/bin/EuroConv.dll

Page ASP.NET

We realize a simple page ASP.NET with form a serveur side that it comprises:

  • cmbCurrency: case to reduction for the selection of the type of currency of departure (Euro or Liras); based on the selected currency it will come invocato the method Euro2Lire() or Lire2Euro()

  • txtValue: case of text for the breaking in of the currency to convert

  • lblResult: label in which visualizing the result of the conversion

  • btnConvert: push-button in order to recall conversion the Web service

The following listato one introduces the code of the page euroconvertitore.aspx, that we will be able to catch up to the address http://localhost/consumer/euroconvertitore.aspx:

<%@ Page Language="C#"%>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Collections" %>
<%@ import Namespace="System.ComponentModel" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Drawing" %>
<%@ import Namespace="System.Web" %>
<%@ import Namespace="System.Web.SessionState" %>
<%@ import Namespace="System.Web.UI" %>
<%@ import Namespace="System.Web.UI.WebControls" %>
<%@ import Namespace="System.Web.UI.HtmlControls" %>
<script runat="server">
    public void Convert(Object sender, EventArgs e)
    {
        EuroConv converter = new EuroConv();
        string res = "";
        string currency = "";
        if(cmbCurrency.SelectedItem.Text.ToLower() == "euro")
        {
            double val = System.Double.Parse(txtValue.Text);
            res = converter.Euro2Lire(val).ToString();
            currency = "Lire";
        }
        else
        {
            int val = System.Int32.Parse(txtValue.Text);
            res = converter.Lire2Euro(val).ToString();
            currency = "Euro";
        }
        lblResult.Text = res " " currency;
        converter = null;
    }
</script>
<html>
<head>
    <title>Euro Convertitore</title>
</head>
<body>
    <form method="post" runat="server">
        <asp:DropDownList id="cmbCurrency" runat="server">
            <asp:ListItem Value="Euro" Selected="True">Euro</asp:ListItem>
            <asp:ListItem Value="Lire" Selected="False">Lire</asp:ListItem>
        </asp:DropDownList>
        <asp:TextBox id="txtValue" runat="server" text=""></asp:TextBox>
        <br />
        <asp:Button id="btnConvert" onclick="Convert" runat="server" Text="converti..." Width="54px"></asp:Button>
        <asp:Label id="lblResult" runat="server" BorderWidth="1px" BorderColor="Gray" BorderStyle="Solid" Width="142px"></asp:Label>
    </form>
</body>
</html>

You notice yourself that the object "EuroConv" comes used as normal class of the application was one:

EuroConv converter = new EuroConv();

The result will be following:

Page ASP.NET consumer of the Web service

Client Windows

We realize hour analogous a Windows application to the Web page of which over.
We open Visual Study NET and we create a new "Plan C # - Windows Application" with name "EuroConvertitore". Rinominiamo Form1 in frmEuro and posizioniamo to the inside of form the controls:

  • cmbCurrency: case to reduction for the selection of the type of currency of departure with two Items: Euro and Liras; based on the selected currency it will come invocato the method Euro2Lire() or Lire2Euro()

  • txtValue: case of text for the breaking in of the currency to convert

  • lblResult: label in which visualizing the result of the conversion

  • btnConvert: push-button in order to recall conversion the Web service

Form the Windows in modalità"Progettazione"

Visual Study NET allows to use in simple and intuitivo way inner a Web service al' of our application; he is in fact sufficient to use the procedure guided for the insertion of a new Web reference, raggiungibile indifferently from the mený "Plan - You add to Web reference..." or from the contestuale mený (skillful key of the mouse) of "References" in the window "Explores solutions" (you see Fig. 6)
In the wizard that it comes to us proposed he is sufficient to specify the address of the web service (in our example: http://localhost/webservice/euroconv.asmx) and to confirm pressing the key "You add reference"

Adding of a Web reference to the service

We make double click on the push-button "you convert..." (btnConvert) and we insert code C # in order to carry out the conversion of the currency using the Web service:

private void btnConvert_Click(object sender, System.EventArgs e)
{
    EuroConvertitore.localhost.EuroConv converter = new EuroConvertitore.localhost.EuroConv();
    string res = "";
    string currency = "";
    if(cmbCurrency.Text.ToLower() == "euro")
    {
        double val = System.Double.Parse(txtValue.Text);
        res = converter.Euro2Lire(val).ToString();
        currency = "Lire";
    }
    else
    {
        int val = System.Int32.Parse(txtValue.Text);
        res = converter.Lire2Euro(val).ToString();
        currency = "Euro";
    }
    lblResult.Text = res " " currency;
    converter = null;
}

To this point it does not remain to us that to compile our application selecting "It generates EuroConvertitore" from the mený "Generates" of Visual Study NET.