Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Utilizar el Protocolo SOAP 1.

ASP.NET Web Services soporta tanto SOAP 1.1 como SOAP 1.2. Por defecto, cada protocolo tendrá un vínculo en el wsdl
producido para el servicio. Para funcionar, o dejar de hacerlo, en SOAP 1.1 o SOAP 1.2, tendremos que modificar las
opciones de configuración tanto en el machine.config como en el web.config. Descomentando las líneas del siguiente
ejemplo deshabilitaremos el soporte para SOAP 1.1 o SOAP 1.2 respectivamente.

<system.web>
<webServices>
<protocols>
<!-- <remove name="HttpSoap"/> -->
<!-- <remove name="HttpSoap1.2"/> -->
</protocols>
</webServices>
</system.web>

C# Sample Caption.

View Source
This file is part of the Microsoft .NET Framework SDK Code Samples.

Copyright (C) Microsoft Corporation. All rights reserved.

This source code is intended only as a supplement to Microsoft


Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY


KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
---------------------------------------------------------------------
-->

<%@ page language="C#" debug="true" %>

<script runat="server">

public void SOAP11_Click(Object sender, EventArgs E)


{
HelloWorldService service = new HelloWorldService();
//Change this URL if the location of the Web service changes
service.Url =
"http://quickstarts.asp.net/QuickStartv20/webservices/Samples/ChooseProto
col/cs/Server/HelloWorldService.asmx";
//This defines the SOAP protocol version to use (Soap 1.1 in this
case)
service.SoapVersion =
System.Web.Services.Protocols.SoapProtocolVersion.Soap11;
try
{
output.Text = service.HelloWorld() + " (using SOAP 1.1)";
}
catch (Exception exception)
{
output.Text = "Received error: " + exception.Message;
}
}

public void SOAP12_Click(Object sender, EventArgs E)


{
HelloWorldService service = new HelloWorldService();
//Change this URL if the location of the Web service changes
service.Url =
"http://quickstarts.asp.net/QuickStartv20/webservices/Samples/ChooseProto
col/cs/Server/HelloWorldService.asmx";
//This defines the SOAP protocol version to use (Soap 1.2 in this
case)
service.SoapVersion =
System.Web.Services.Protocols.SoapProtocolVersion.Soap12;
try
{
output.Text = service.HelloWorld() + " (using SOAP 1.2)";
}
catch (Exception exception)
{
output.Text = "Received error: " + exception.Message;
}
}

</script>

<body>
<form id="form1" runat="server">
<p><font face="Verdana" size="-1">Use SOAP 1.1 or SOAP 1.2 to
make your Web service call. </p>
<p> Modify web.config (in the 'server' subdirectory) to turn on or
off Soap 1.1 and Soap 1.2.</font></p>
<p><input id="SOAP11" type="submit" value="SOAP 1.1"
onserverClick="SOAP11_Click" runat="server" /></p>
<p><input id="SOAP12" type="submit" value="SOAP 1.2"
onserverClick="SOAP12_Click" runat="server" /></p>
<p><b><font face="Verdana" size="-1">Output:</font></b>
<font face="Verdana" size="-1" color='red'><asp:Label id="output"
text="" runat="server"/></font></p>
</form>
</body>
</html>
Devolver Varios Tipos de Datos

ASP.NET Web Services nos da una gran flexibilidad para estructurar los mensajes que se pasan hacía y desde un Servicio
Web. Este ejemplo muestra ejemplos de WebMethods que devuelven los siguientes tipos de datos:

• Primitive (String)
• Array of Primitives (Integers)
• Enumeration (Enum)
• Class/Struct
• Array of Classes/Structs

This file is part of the Microsoft .NET Framework SDK Code Samples.

Copyright (C) Microsoft Corporation. All rights reserved.

This source code is intended only as a supplement to Microsoft


Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY


KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
---------------------------------------------------------------------
-->

<%@ Page Language="C#" Debug="true" %>

<html>
<style>

div
{
font: 8pt verdana;
background-color:cccccc;
border-color:black;
border-width:1;
border-style:solid;
padding:10,10,10,10;
}

</style>

<script language="C#" runat="server">

public void Page_Load(Object sender, EventArgs E)


{
DataTypes dataTypeService = new DataTypes();
//change this URL if the location of the Web service changes
dataTypeService.Url =
"http://quickstarts.asp.net/quickstartv20/webservices/Samples/DataTypes/c
s/server/DataTypes.asmx";
Message1.InnerHtml = "Call 1:<BR>" + dataTypeService.SayHello() +
"<BR><BR>";
Message1.InnerHtml += "Call 2:<BR>" +
dataTypeService.SayHelloName("Bob");

int[] myIntArray = dataTypeService.GetIntArray();


String myString = "Contents of the Array:<BR>";
for( int i=0; i<myIntArray.Length; i++)
{
myString = myString + myIntArray[i] + "<BR>";
}
Message2.InnerHtml = Message2.InnerHtml + myString;

Message3.InnerHtml = "Enum Value: <BR>" +


dataTypeService.GetMode();

Order myOrder = dataTypeService.GetOrder();


Message4.InnerHtml = "OrderID: " + myOrder.OrderID;
Message4.InnerHtml += "<BR>Price: " + myOrder.Price;

Order[] myOrders = dataTypeService.GetOrders();


for( int i=0; i<myOrders.Length; i++) {
if ( i > 0 ) { Message5.InnerHtml += "<BR>"; }
Message5.InnerHtml += "Order#: " + i;
Message5.InnerHtml += "<BR>OrderID: " + myOrders[i].OrderID;
Message5.InnerHtml += "<BR>Price: " + myOrders[i].Price +
"<BR>";
}

</script>

<body style="font: 10pt verdana">


<H4>Using DataTypes with XML Web services</H4>

<h5>Two Methods that return a Primitive (String): </h5>


<div id="Message1" runat="server"/>

<h5>Method that returns an Array of Primitives (Integers): </h5>


<div id="Message2" runat="server"/>

<h5>Method that returns an Enum: </h5>


<div id="Message3" runat="server"/>

<h5>Method that returns a Class/Struct: </h5>


<div id="Message4" runat="server"/>

<h5>Method that returns an array of Classes/Structs: </h5>


<div id="Message5" runat="server"/>

</body>
</html>
Permitir la DesCompresión de Servicios
Web

Sencillo Servicio Web que Muestra la Función EnableDecompression

Cuando la propiedad EnableDecompression de una instancia de un cliente de una clase proxy se establece a verdadero, el
cliente soportará la descompresión.

EnableDecompressionService service = new EnableDecompressionService();


service.EnableDecompression = true;
Esto nos da la habilidad de interoperar con servicios que soporten la compresión.

Para deshabilitar la descompresión, tendremos que establecer EnableDecompression a falso. Un probable escenario dónde
pasa esto es cuando queremos ver las trazas SOAP de las respuestas enviadas desde el servidor, en texto plano.
Estableciendo la propiedad a falso, permitimos que el servidor sepa que la descompresión no se soporta.

NOTA: El Servicio Web de este ejemplo no soporta compresión.

View Source

This file is part of the Microsoft .NET Framework SDK Code Samples.

Copyright (C) Microsoft Corporation. All rights reserved.

This source code is intended only as a supplement to Microsoft


Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY


KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
---------------------------------------------------------------------
-->

<%@ Page Language="VB" Debug="true" %>

<script runat="server">

Public Sub EnableDecompression_Click(sender As Object, E As EventArgs)


Dim service As New EnableDecompressionService()
'Change this URL if the location of the Web service changes
service.Url =
"http://quickstarts.asp.net/QuickStartv20/webservices/Samples/EnableDecom
pression/vb/Server/EnableDecompressionService.asmx"
service.EnableDecompression = True
output.Text = service.HelloWorld()
End Sub 'EnableDecompression_Click

Public Sub Reset_Click(sender As [Object], E As EventArgs)


output.Text = ""
End Sub 'Reset_Click

</script>

<body>
<form id="form1" runat="server">
<p><font face="Verdana" size="-1">When the EnableDecompression
property
on an instance of a client proxy class is set to true the client will
support decompression.</p>
<p><input id="EnableDecompression" type="submit" value="Query
Service" onserverClick="EnableDecompression_Click" runat="server" /></p>
<p><b><font face="Verdana" size="-1">Output:</font></b>
<font face="Verdana" size="-1" color='red'><asp:Label id="output"
text="" runat="server"/></font></p>
<p><input id="Reset" type="submit" value="Reset"
onserverClick="Reset_Click" runat="server" /></p>
</form>
</body>
</html>
Utilizando Sesiones ASP.NET

Intrinsecos (Administración de Sesiones ASP.NET y Estado de la


Aplicación)

Los Servicios Web de ASP.NET nos permiten acceder a la administración de estado subyacente que proporciona ASP.NET.
Para permitir el estado de sesión de ASP.NET tenemos que establecer set WebMethod.EnableSession = True. En el cliente
tendremos que fijar serviceName.CookieContainer a una nueva instancia de System.Net.CookieContainer. Esto nos
permite mantener los datos en la misma sesión. Observar que para mantener los datos para toda la aplicación (para todas
las peticiones entrantes al servicio), no se requiere ningún paso.

Código del Lado del Cliente

//On the client you must add the following code (for session state only):
serviceName.CookieContainer = new System.Net.CookieContainer();

Código del Lado del Servidor

//Setting EnableSession to true allows state to be persisted per Session


[WebMethod(EnableSession=true)]
public String UpdateSessionHitCounter() {
//update the session "HitCounter" here
return Session["HitCounter"].ToString();
}

//Note that state can be persisted for the entire Application even if
EnableSession is false
[WebMethod(EnableSession=false)]
public String UpdateApplicationHitCounter() {
//update the application "HitCounter" here
return Application["HitCounter"].ToString();
}

This file is part of the Microsoft .NET Framework SDK Code Samples.

Copyright (C) Microsoft Corporation. All rights reserved.

This source code is intended only as a supplement to Microsoft


Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY


KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
---------------------------------------------------------------------
-->

<%@ Page Language="C#" Debug="true" %>


<%@ Import Namespace="System.Net" %>

<html>

<style>

div
{
font: 8pt verdana;
background-color:cccccc;
border-color:black;
border-width:1;
border-style:solid;
padding:10,10,10,10;
}

</style>

<script language="C#" runat="server">

public void Page_Load(Object sender, EventArgs E)


{
//Create a new instance of the proxy class
SessionService sessionService = new SessionService();
//Change this URL if the location of the Web service changes
sessionService.Url =
"http://quickstarts.asp.net/QuickStartv20/webservices/Samples/Intrinsics/
cs/server/SessionService.asmx";
//You must set the web service proxy's CookieContainer property to a
new instance
//of System.Net.CookieContainer to enable session state
sessionService.CookieContainer = new System.Net.CookieContainer();

//Make three calls to the service to increment the session hit


counter
//The session hit counter can only be incremented in this session
//If you open the client in a new browser, the hit counter is
back to zero
Message1.InnerHtml = sessionService.UpdateSessionHitCounter() +
"<BR>" + sessionService.UpdateSessionHitCounter() + "<BR>" +
sessionService.UpdateSessionHitCounter();

//Make three calls to the service to increment the application


hit counter
//The application hit counter will be incremented by all sessions
//If you open the client in a new browser, both sessions will
increment the hit counter
Message2.InnerHtml = sessionService.UpdateApplicationHitCounter()
+ "<BR>" + sessionService.UpdateApplicationHitCounter() + "<BR>" +
sessionService.UpdateApplicationHitCounter();
}
</script>

<body style="font: 10pt verdana">


<H4>Using Intrinsics with XML Web services</H4>

<h5>UpdateHitCounter Output: </h5>


<div id="Message1" runat="server"/>

<h5>UpdateAppCounter Output: </h5>


<div id="Message2" runat="server"/>

</body>
</html>
Validación de Mensajes

Servicio Web Que Valida Mensajes Entrantes de Acuerdo con un


Esquema

Para validar los mensajes en el servicio usamos XmlValidatingReader. El mejor lugar para hacerlo es en una extensión
SOAP. Ésto nos da un control completo sobre los contenidos del mensaje SOAP y nos permite descartar mensajes que no
cumplen con el esquema antes del paso de deserialización, relativamente costoso.

Observar que este ejemplo valida los mensajes en el cuerpo del WebMethod. Esto se ha hecho por simplicidad. Los pasos
para validar un mensaje son los mismos independientemente del lugar. Para más información sobre la validación en
extensiones SOAP, acudid a MSDN article.

//create the validating reader


XmlTextReader tr = new XmlTextReader(input, XmlNodeType.Document, null);
XmlValidatingReader vr = new XmlValidatingReader(tr);

//add the schema and set the validation type to schema


XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add("Microsoft.Samples.Web.Services", "insert location here...");
vr.Schemas.Add(schemas);
vr.ValidationType = ValidationType.Schema;

//add our event callback function to the event handler in case there is a
validation error
vr.ValidationEventHandler += new ValidationEventHandler
(ValidationHandler);

try
{
//if there is an error we will fall out of this while loop and our
callback function will be called
while (vr.Read())
{
//do nothing
}
}
catch (Exception exception)
{
//an exception will be thrown if there are non-validation errors,
e.g. in the case of malformed XML
}

This file is part of the Microsoft .NET Framework SDK Code Samples.

Copyright (C) Microsoft Corporation. All rights reserved.


This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY


KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
---------------------------------------------------------------------
-->

<%@ Page Language="C#" ValidateRequest=false Debug="true" %>


<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Serialization" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">

public void Button1_Click(Object sender, EventArgs E)


{
Book book = new Book();
book.Author = BookAuthor.Value;
book.Title = BookTitle.Value;

try
{
//First, create the xml to send using the Xml Serializer
XmlSerializer xs = new XmlSerializer(typeof(Book),
"Microsoft.Samples.Web.Services");
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
xs.Serialize(writer, book);
writer.Close();
string serializedContent = builder.ToString();
EditXML.Text = serializedContent;
}
catch (Exception exception)
{
output.Text = "Received error: " + exception.Message;
}
}

public void Button2_Click(Object sender, EventArgs E)


{
string response = "";
MessageValidationService service = new MessageValidationService();
//Change this URL if the location of the Web service changes
service.Url =
"http://quickstarts.asp.net/QuickStartv20/webservices/Samples/MessageVali
dation/cs/Server/MessageValidationService.asmx";

try
{
response = service.SendToValidator(EditXML.Text);
output.Text = response;
}
catch (Exception exception)
{
output.Text = "Received error: " + exception.Message;
}
}

public void Button3_Click(Object sender, EventArgs E)


{
//this simply resets the sample to its original state
BookAuthor.Value = "";
BookTitle.Value = "";
EditXML.Text = "";
output.Text = "";
}

</script>

<html>

<body>
<form id="form1" runat="server">
<font face="Verdana">
<p><font size="-1"><b>Step 1:</b> Enter the title and author of
your favorite book and then click <b>Generate XML</b>.</font></p>
<p><b>Book Title: </b><input type=text id="BookTitle" value=""
runat="server"/><br>
<b>Book Author: </b><input type=text id="BookAuthor" value=""
runat="server"/></p>
<p><input id="GenerateButton" type="submit" value="Generate XML"
onserverClick="Button1_Click" runat="server" /></p>
<p><font size="-1"><b>Step 2:</b> Consider editing the generated
XML to make it malformed or not comply with the <a
href="../../Book.xsd">Book schema</a>. If you do not make any edits
validation will be successful.</font></p>
<b>Edit XML:</b><br /><asp:TextBox Rows=5 TextMode=MultiLine
Height=125 Width=500 id="EditXML" Wrap=true runat=server/></p>
<p><input id="SubmitButton" type="submit" value="Submit"
onserverClick="Button2_Click" runat="server" />
&nbsp;&nbsp;<input id="ResetButton" type="submit" value="Reset"
onserverClick="Button3_Click" runat="server" /></p>
<p><b><font size="-1">Response (from Web service):</font></b><br>
<font size="-1" color='red'><asp:Label id="output" text=""
runat="server"/></font></p>
</font>
</form>
</body>

</html>

You might also like