Un servicio web sencillo con .NET 2.0

He aquí un pequeño ejemplo de web services para .NET 2.0 que lo puedes poner en práctica fácil y rápidamente.

Tendremos tres bloques de código:

  • Los métodos del servicio
  • La página que utiliza el servicio

El primer archivo que hay que hacer es la página .aspx, a la que (por simplicidad) insertaremos directamente el código C#. Se llamará, por ejemplo, test.aspx:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script type="text/C#" runat="server">
  [WebMethod]
  // Get session state value.
  public static string GetSessionValue(string key)
  {
    return (string)HttpContext.Current.Session[key];
  }
  [WebMethod]
  // Set session state value.
  public static string SetSessionValue(string key, string value)
  {
    HttpContext.Current.Session[key] = value;
    return (string)HttpContext.Current.Session[key];
  }
</script>

<html>
<head id="Head1" runat="server">
  <title>Using Page Methods with Session State</title>
</head>
<body>
  <h2>
    Using Page Methods with Session State</h2>
  <form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1"
    runat="server" EnablePageMethods="true">
    <Scripts>
      <asp:ScriptReference Path="_PageMethods.js" />
    </Scripts>
  </asp:ScriptManager>
  </form>
  <center>
    <table>
      <tr align="left">
        <td>
          Write current date and time in session state:
        </td>
        <td>
          <input type="button" onclick="SetSessionValue
            ('SessionValue', Date())" value="Write" />
        </td>
      </tr>
      <tr align="left">
        <td>
          Read current date and time from session state:
        </td>
        <td>
          <input type="button" onclick="GetSessionValue
            ('SessionValue')" value="Read" />
        </td>
      </tr>
    </table>
  </center>
  <hr />
  <span style="background-color: Aqua" id="ResultId"></span>
</body>
</html>

El segundo sería PageMethods.js y llevaría el siguiente código:

var displayElement;
// Initializes global variables and session state.
function pageLoad()
{ displayElement = $get("ResultId");
  PageMethods.SetSessionValue("SessionValue", Date(),
    OnSucceeded, OnFailed);
}
// Gets the session state value.
function GetSessionValue(key)
{ PageMethods.GetSessionValue(key,
  OnSucceeded, OnFailed);
}
//Sets the session state value.
function SetSessionValue(key, value)
{ PageMethods.SetSessionValue(key, value,
    OnSucceeded, OnFailed);
}

// Callback function invoked on successful
// completion of the page method.
function OnSucceeded(result, userContext, methodName)
{
  if (methodName == "GetSessionValue")
  { displayElement.innerHTML = "Current session state value: " +
    result;
  }
}
// Callback function invoked on failure
// of the page method.
function OnFailed(error, userContext, methodName)
{ if(error !== null)
  { displayElement.innerHTML = "An error occurred: " + error.get_message();
  }
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Otros artículos de esta serie:

[seriesposts show_date=0 order=asc]

Publicar un Comentario

Si es la primera vez que escribes, tu comentario será moderado por un administrador.

Con el fin de garantizar un ambiente de debate respetuoso, no se permitirán comentarios:

  • insultantes, difamatorios, racistas, sexistas, y/o discriminatorios
  • excesivamente críticos con otros participanes
  • que no aporten nada, sin sentido o repetidos
  • con enlaces considerados publicidad o spam
  • con material protegido por derechos de autor
*
*