WCF: creación del servicio WCF

Crear un servicio WCF es una tarea sencilla con Microsoft Visual Studio 2012. A continuación se muestra el método paso a paso para crear un servicio WCF junto con toda la codificación necesaria, para comprender el concepto de una mejor manera.

  • Inicie Visual Studio 2012.
  • Haga clic en nuevo proyecto, luego en la pestaña Visual C #, seleccione la opción WCF.

Se crea un servicio WCF que realiza operaciones aritméticas básicas como suma, resta, multiplicación y división. El código principal está en dos archivos diferentes: una interfaz y una clase.

Un WCF contiene una o más interfaces y sus clases implementadas.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfServiceLibrary1 {
   // NOTE: You can use the "Rename" command on the "Refactor" menu to 
   // change the interface name "IService1" in both code and config file 
   // together.

   [ServiceContract]
   Public interface IService1 {
      [OperationContract]
      int sum(int num1, int num2);

      [OperationContract]
      int Subtract(int num1, int num2);

      [OperationContract]
      int Multiply(int num1, int num2);

      [OperationContract]
      int Divide(int num1, int num2);
   }

   // Use a data contract as illustrated in the sample below to add 
   // composite types to service operations.

   [DataContract]
   Public class CompositeType {
      Bool boolValue = true;
      String stringValue = "Hello ";

      [DataMember]
      Public bool BoolValue {
         get { return boolValue; }
         set { boolValue = value; }
      }

      [DataMember]   
      Public string StringValue {
         get { return stringValue; }
         set { stringValue = value; }
      }
   }
}

El código detrás de su clase se proporciona a continuación.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.Text;

namespace WcfServiceLibrary1 {
   // NOTE: You can use the "Rename" command on the "Refactor" menu to 
   // change the class name "Service1" in both code and config file 
   // together.

   publicclassService1 :IService1 {
      // This Function Returns summation of two integer numbers
      
      publicint sum(int num1, int num2) {
         return num1 + num2;
      }
      
      // This function returns subtraction of two numbers. 
      // If num1 is smaller than number two then this function returns 0
      
      publicint Subtract(int num1, int num2) {
         if (num1 > num2) {
            return num1 - num2;
         }
         else {
            return 0;
         }
      }
      
      // This function returns multiplication of two integer numbers.
      publicint Multiply(int num1, int num2) {
         return num1 * num2;
      }
      
      // This function returns integer value of two integer number. 
      // If num2 is 0 then this function returns 1.
      publicint Divide(int num1, int num2) {
         if (num2 != 0) {
            return (num1 / num2);
         } else {
            return 1;
         }
      }
   }
}

Para ejecutar este servicio, haga clic en el botón Inicio en Visual Studio.

Mientras ejecutamos este servicio, aparece la siguiente pantalla.

Al hacer clic en el método de suma, se abre la siguiente página. Aquí, puede ingresar dos números enteros cualesquiera y hacer clic en el botón Invocar. El servicio devolverá la suma de esos dos números.

Como la suma, podemos realizar todas las demás operaciones aritméticas que se enumeran en el menú. Y aquí están las instantáneas para ellos.

La siguiente página aparece al hacer clic en el método Restar. Ingrese los números enteros, haga clic en el botón Invocar y obtenga el resultado como se muestra aquí:

La siguiente página aparece al hacer clic en el método Multiplicar. Ingrese los números enteros, haga clic en el botón Invocar y obtenga el resultado como se muestra aquí:

La siguiente página aparece al hacer clic en el método Dividir. Ingrese los números enteros, haga clic en el botón Invocar y obtenga el resultado como se muestra aquí:

Una vez que se llama al servicio, puede cambiar entre ellos directamente desde aquí.