Compartir a través de


Tutorial: Usar servicios de aplicación ASP.NET

Actualización: noviembre 2007

ASP.NET proporciona servicios de aplicación en web que permiten a las aplicaciones cliente tener acceso a la información de autenticación, función y perfil de usuario. Las aplicaciones cliente que se escriben en lenguajes diferentes y que se ejecutan en sistemas operativos diferentes pueden tener acceso a esta información. El único requisito es que estos clientes deben poder comunicar a través del protocolo SOAP 1.1.

Este tutorial está dividido en las partes siguientes:

  • La parte 1 muestra cómo configurar un sitio web ASP.NET para exponer los servicios de aplicación.

  • La parte 2 muestra cómo generar una aplicación de consola de Windows con acceso a la información de autenticación, funciones y perfil de un usuario. En este tutorial generará una aplicación de consola de Windows, pero los servicios de la aplicación ASP.NET están disponibles para todas las aplicaciones cliente que pueden enviar y recibir mensajes en formato SOAP.

Requisitos previos

Para completar las tareas de este tutorial, necesitará:

  • Visual Studio 2008. No puede usar Microsoft Visual Web Developer 2005 para este tutorial porque creará una aplicación de consola de Windows, que no se admite en Visual Web Developer Express.

  • Microsoft SQL Server o SQL Server Express Edition instalado en el equipo.

Exponer los servicios de aplicación

En esta sección se describe cómo exponer los servicios de aplicación como parte de un sitio web ASP.NET para que cualquier cliente pueda tener acceso a ellos en la red. Los pasos descritos aquí solo se aplican al servidor.

Nota:

En este tutorial debe usar un sitio web del sistema de archivos. En este tutorial se da por supuesto que usa el Servidor de desarrollo de ASP.NET en lugar de IIS para ejecutar los ejemplos. Para obtener más información, vea Servidores Web en Visual Web Developer.

Para crear el sitio web de los servicios de aplicación

  1. Abra Visual Studio 2008.

  2. En el menú Archivo, haga clic en Nuevo sitio Web.

    Aparece el cuadro de diálogo Nuevo sitio Web.

  3. En Plantillas instaladas de Visual Studio, seleccione Sitio Web de ASP.NET.

  4. En la lista Ubicación, seleccione Sistema de archivos.

  5. En el cuadro de texto Carpeta, asigne el nombre WcfApplicationServices al sitio web.

    Nota:

    Puede usar cualquier nombre. Si usa un nombre diferente, anote el nombre para poder sustituirlo cuando sea necesario más adelante en este tutorial.

  6. Haga clic en Aceptar.

    Visual Studio crea un nuevo sitio web ASP.NET y abre la página Default.aspx.

  7. En el Explorador de soluciones, haga clic en el nombre del sitio web y, a continuación, presione F4 para abrir la ventana Propiedades.

  8. En la ventana Propiedades, establezca Usar puertos dinámicos en False.

    Esto indica a Visual Studio que especifique un puerto fijo en lugar de un puerto seleccionado de forma aleatoria cuando inicie el servidor de desarrollo de ASP.NET. En este tutorial, debe tener un número de puerto fijo que pueda usar al generar las clases de proxy de cliente y los archivos de configuración. Para obtener más información, vea Cómo: Especificar un puerto para el servidor de desarrollo de ASP.NET.

    Nota:

    No es posible obtener acceso a la ventana Propiedades del sitio web desde la ventana Páginas de propiedades.

  9. Establezca el Número de puerto en 8080.

    Nota:

    Puede usar cualquier puerto disponible. Si usa un puerto diferente, anote el número de puerto para sustituir 8080 por ese número más adelante en este tutorial.

La información de pertenencia, función y perfil de ASP.NET se almacena en una base de datos. Esta base de datos se crea automáticamente cuando se necesita. En el procedimiento siguiente, creará usuarios y funciones para la aplicación, que creará automáticamente la base de datos.

Para crear usuarios e información de funciones

  1. Agregue un archivo Global.asax al sitio web y, en dicho archivo, reemplace el método Application_Start existente con el código siguiente:

    <%@ Application Language="VB" %>
    
    <script >
    
        Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs on application startup
            ' Warning. This code is just for test purposes 
            ' to generate a SQL Express database quickly.
            ' In a production environment, you must set 
            ' a SQL standard database separately.
            If Not Roles.RoleExists("Administrators") Then
                Roles.CreateRole("Administrators")
            End If
            If Not Roles.RoleExists("Friends") Then
                Roles.CreateRole("Friends")
            End If
        End Sub
    
    
    </script>
    
    
    <%@ Application Language="C#" %>
    
    <script >
    
        void Application_Start(object sender, EventArgs e) 
        {
            // Code that runs on application startup
            // Warning. This code is just for test purposes 
            // to generate a SQL Express database quickly.
            // In a production environment, you must set   3-25
            // a SQL standard database separately.
            if (!Roles.RoleExists("Administrators")){
                Roles.CreateRole("Administrators");
    
            }
            if (!Roles.RoleExists("Friends")){
                Roles.CreateRole("Friends");
    
            }
    
        }
    
    
    </script>
    
    

    La primera vez que ejecuta la aplicación web, el código crea la base de datos local Aspnetdb.mdf y agrega a ésta las funciones Administrators y Friends. Esta base de datos se usa para almacenar credenciales de usuario, funciones e información de perfil.

  2. Abra la página Default.aspx y agregue a ésta el marcado que se indica a continuación. De esta forma se agregan vínculos para las páginas de inicio de sesión, de información de perfil y de nuevo usuario. Estas páginas se agregarán más adelante en este tutorial.

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" >
        <title>Application Services Home Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <h2>Enter Users' Information</h2>
    
            The following selections enable you to create users, and assign them roles and
            profile information.
    
            <p>
                <asp:Label ID="LoggedId"  Font-Bold="true" ForeColor="red" />
            </p>
    
            <table border="1">
                <tr>
                    <td align="left">Login to change profile</td>
                    <td align="left"><asp:LoginStatus ID="LoginStatus1"  /></td>
                </tr>
                <tr>
                    <td align="left">Define profile information (you must login first)</td>
                    <td align="left"><a href="Profile.aspx" target="_self">Profile Information</a></td>
                </tr>
                <tr>
                    <td align="left">Create user and assign role</td>
                    <td align="left"><a href="CreateUser.aspx"target="_self">New User</a></td>
                </tr>
    
             </table>
        </div>
    
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
        <title>Application Services Home Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <h2>Enter Users' Information</h2>
    
        The following selections enable you to create users, and assign them roles and
            profile information.
    
            <p>
                <asp:Label ID="LoggedId"  Font-Bold="true" ForeColor="red" />
            </p>
    
            <table border="1">
                <tr>
                    <td align="left">Login to change profile</td>
                    <td align="left"><asp:LoginStatus ID="LoginStatus1"  /></td>
                </tr>
                <tr>
                    <td align="left">Define profile information (you must login first)</td>
                    <td align="left"><a href="Profile.aspx" target="_self">Profile Information</a></td>
                </tr>
                <tr>
                    <td align="left">Create user and assign role</td>
                    <td align="left"><a href="CreateUser.aspx"target="_self">New User</a></td>
                </tr>
    
             </table>
        </div>
    
        </form>
    </body>
    </html>
    
  3. En el archivo de código subyacente Default.aspx, agregue código al método Page_Load que compruebe si el usuario está autenticado.

    En el ejemplo siguiente se muestra cómo comprobar si un usuario está autenticado.

    Imports System
    Imports System.Data
    Imports System.Configuration
    Imports System.Collections
    Imports System.Web
    Imports System.Web.Security
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports System.Web.UI.HtmlControls
    
    Partial Public Class _Default
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                LoggedId.Text = HttpContext.Current.User.Identity.Name + " you are logged in"
            End If
    
        End Sub
    End Class
    
    
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                LoggedId.Text = HttpContext.Current.User.Identity.Name +
                    " you are logged in";
            }
    
        }
    }
    
  4. Agregue una página denominada Login.aspx. Asegúrese de que la opción Colocar el código en un archivo independiente esté seleccionada.

  5. Agregue un control Login al archivo Login.aspx.

    En el ejemplo siguiente se muestra el marcado del archivo Login.aspx.

    <%@ Page Language="VB" AutoEventWireup="true" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
        <title>Login Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <asp:Login ID="Login1"    />
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
        <title>Login Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <asp:Login ID="Login1"   />
        </div>
        </form>
    </body>
    </html>
    
  6. Añada una página denominada Profile.aspx, y asegúrese de que la opción Colocar el código en un archivo independiente esté seleccionada.

  7. Agregue el marcado siguiente a la página Profile.aspx:

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Profile.aspx.vb" Inherits="_Profile" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" >
        <title>Profile Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <h3>Current Authenticated User Profile Information</h3> 
    
            <a href="Default.aspx">back to default page</a>
    
            <h4>Read Profile Information</h4>
            <table>
                <tr>
                    <td align="left">User Name</td>
                    <td align="left">
                        <asp:Label ID="Label1"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">User Roles</td>
                    <td align="left">
                        <asp:Label ID="Label2"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">First Name</td>
                    <td>
                        <asp:Label ID="Label3"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td>    
                        <asp:Label ID="Label4"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td>    
                        <asp:Label ID="Label5"  Text="Label"/>
                    </td>
                </tr>
    
            </table>
            <asp:Button ID="Button2"  onclick="Button2_Click" 
                Text="Read Profile Information" />
    
            <hr />
    
            <h3>Update Profile Information </h3>
    
            <table>
                <tr>
                    <td align="left">First Name</td>
                    <td align="left"><asp:TextBox ID="TextBox1" /></td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td align="left"><asp:TextBox ID="TextBox2" /></td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td align="left"><asp:TextBox ID="TextBox3" /></td>
                </tr>
    
            </table>
    
            <asp:Button ID="Button1"  onclick="Button1_Click" 
            Text="Update Profile Data" />
    
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="Profile.aspx.cs" Inherits="ProfileInformation" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" >
        <title>Profile Page</title>
    </head>
    <body>
        <form id="form1" >
        <div>
            <h3>Current Authenticated User Profile Information</h3> 
    
            <a href="Default.aspx">back to default page</a>
    
            <h4>Read Profile Information</h4>
            <table>
                <tr>
                    <td align="left">User Name</td>
                    <td align="left">
                        <asp:Label ID="Label1"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">User Roles</td>
                    <td align="left">
                        <asp:Label ID="Label2"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">First Name</td>
                    <td>
                        <asp:Label ID="Label3"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td>    
                        <asp:Label ID="Label4"  Text="Label"/>
                    </td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td>    
                        <asp:Label ID="Label5"  Text="Label"/>
                    </td>
                </tr>
    
            </table>
            <asp:Button ID="Button2"  onclick="Button2_Click" 
                Text="Read Profile Information" />
    
            <hr />
    
            <h3>Update Profile Information </h3>
    
            <table>
                <tr>
                    <td align="left">First Name</td>
                    <td align="left"><asp:TextBox ID="TextBox1" /></td>
                </tr>
                <tr>
                    <td align="left">Last Name</td>
                    <td align="left"><asp:TextBox ID="TextBox2" /></td>
                </tr>
                <tr>
                    <td align="left">ID#</td>
                    <td align="left"><asp:TextBox ID="TextBox3" /></td>
                </tr>
    
            </table>
    
            <asp:Button ID="Button1"  onclick="Button1_Click" 
            Text="Update Profile Data" />
    
        </div>
        </form>
    </body>
    </html>
    

    La página Profile contiene controles Label que se usan para mostrar el nombre y la función del usuario, además de controles TextBox que se usan para cambiar el nombre y el identificador de los usuarios.

  8. Agregue el código siguiente en el archivo de código subyacente para la página Profile.aspx:

    Imports System
    Imports System.Data
    Imports System.Configuration
    Imports System.Collections
    Imports System.Web
    Imports System.Web.Security
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports System.Web.UI.HtmlControls
    
    Partial Public Class _Profile
        Inherits System.Web.UI.Page
    
        Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    
             Dim Profile As ProfileCommon = TryCast(HttpContext.Current.Profile, ProfileCommon)
    
            If HttpContext.Current.User.Identity.IsAuthenticated Then
    
                Label1.Text = HttpContext.Current.User.Identity.Name
                Dim roles As String() = _
                    System.Web.Security.Roles.GetRolesForUser()
    
                Label2.Text = ""
                For Each r As String In roles
                    Label2.Text += r + " "
                Next
    
                Label3.Text = Profile.FirstName()
                Label4.Text = Profile.LastName
    
                Label5.Text = Profile.EmployeeId
            Else
                Label1.Text = "User is not Authenticated"
                Label1.ForeColor = System.Drawing.Color.Red
            End If
        End Sub
    
        Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                Label1.Text = HttpContext.Current.User.Identity.Name
                Dim roles As String() = _
                    System.Web.Security.Roles.GetRolesForUser()
                Label2.Text = ""
                For Each r As String In roles
                    Label2.Text += r + " "
                Next
                Label3.Text = Profile.FirstName
                Label4.Text = Profile.LastName
                Label5.Text = Profile.EmployeeId
            Else
                Label1.Text = "User is not Authenticated"
                Label1.ForeColor = System.Drawing.Color.Red
            End If
        End Sub
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                Profile.FirstName = TextBox1.Text
                Profile.LastName = TextBox2.Text
                Profile.EmployeeId = TextBox3.Text
            End If
        End Sub
    End Class
    
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class ProfileInformation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
         ProfileCommon Profile = HttpContext.Current.Profile
                                      as ProfileCommon;
    
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Label1.Text = HttpContext.Current.User.Identity.Name;
                string[] roles = Roles.GetRolesForUser();
                Label2.Text = "";
                foreach (string r in roles)
                {
                    Label2.Text += r + " ";
                }
    
                Label3.Text = Profile.FirstName;
                Label4.Text = Profile.LastName;
                Label5.Text = Profile.EmployeeId;
    
            }
            else
            {
                Label1.Text = "User is not Authenticated";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }
    
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Label1.Text = HttpContext.Current.User.Identity.Name;
                string[] roles = Roles.GetRolesForUser();
                Label2.Text = "";
                foreach (string r in roles)
                {
                    Label2.Text += r + " ";
                }
    
                Label3.Text = Profile.FirstName;
                Label4.Text = Profile.LastName;
                Label5.Text = Profile.EmployeeId;
    
            }
            else
            {
                Label1.Text = "User is not Authenticated";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Profile.FirstName = TextBox1.Text;
                Profile.LastName = TextBox2.Text;
                Profile.EmployeeId = TextBox3.Text;
            }
        }
    }
    
    Nota:

    En el ejemplo anterior, el nombre de la clase del archivo de código subyacente se ha cambiado a _Profile para evitar que entre en conflicto con la instancia de Profile.

    El código de esta página permite obtener y cambiar información de perfil de usuario.

    Nota:

    El proyecto no se compilará hasta que habilite las propiedades de perfil para el sitio web. Hará esto en el procedimiento siguiente.

  9. Agregue una página denominada CreateUser.aspx y agregue el marcado siguiente en ella:

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="CreateUser.aspx.vb" Inherits="CreateUser" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
        <title>Add New User</title>
    </head>
    <body>
        <form id="form1" >
        <div>
    
            <h2>Add New User</h2>
    
            <a href="Default.aspx">back to default page</a>
    
            <asp:CreateUserWizard ID="CreateUserWizard1" 
              OnCreatedUser="On_CreatedUser">
                <wizardsteps>
                    <asp:CreateUserWizardStep ID="CreateUserWizardStep1"   />
                    <asp:CompleteWizardStep ID="CompleteWizardStep1"   />
                </wizardsteps>
            </asp:CreateUserWizard>
            <p> 
                Check the following box to assign the user to the administrator role.
                Otherwise, the user will be assigned to the friends role by default. 
            </p>
            <span style="font-weight:bold; color:Red">Administrator</span> 
            <asp:CheckBox ID="CheckBox1"  />
    
        </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="CreateUser.aspx.cs" Inherits="CreateUser" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" >
        <title>Add New User</title>
    </head>
    <body>
        <form id="form1" >
        <div>
    
            <h2>Add New User</h2>
    
            <a href="Default.aspx">back to default page</a>
    
            <asp:CreateUserWizard ID="CreateUserWizard1" 
              OnCreatedUser="On_CreatedUser">
                <wizardsteps>
                    <asp:CreateUserWizardStep ID="CreateUserWizardStep1"   />
                    <asp:CompleteWizardStep ID="CompleteWizardStep1"   />
                </wizardsteps>
            </asp:CreateUserWizard>
            <p> 
                Check the following box to assign the user to the administrator role.
                Otherwise, the user will be assigned to the friends role by default. 
            </p>
            <span style="font-weight:bold; color:Red">Administrator</span> 
            <asp:CheckBox ID="CheckBox1"  />
    
        </div>
        </form>
    </body>
    </html>
    
  10. Agregue el código siguiente en el archivo de código subyacente para la página CreateUser.aspx:

    Imports System
    Imports System.Data
    Imports System.Configuration
    Imports System.Collections
    Imports System.Web
    Imports System.Web.Security
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports System.Web.UI.HtmlControls
    
    Partial Public Class CreateUser
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    
        End Sub
    
        Protected Sub On_CreatedUser(ByVal sender As Object, ByVal e As EventArgs)
            Dim userName As String = CreateUserWizard1.UserName
            If CheckBox1.Checked Then
                HttpContext.Current.Response.Write(userName)
                Roles.AddUserToRole(userName, "Administrators")
            Else
                Roles.AddUserToRole(userName, "Friends")
            End If
    
            CheckBox1.Visible = False
    
            HttpContext.Current.Response.Redirect("~/default.aspx")
        End Sub
    End Class
    
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class CreateUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        protected void On_CreatedUser(object sender, EventArgs e)
        {
            string userName = CreateUserWizard1.UserName;
            if (CheckBox1.Checked)
            {
                HttpContext.Current.Response.Write(userName);
                Roles.AddUserToRole(userName, "Administrators");
            }
            else
                Roles.AddUserToRole(userName, "Friends");
    
            CheckBox1.Visible = false;
    
            HttpContext.Current.Response.Redirect("~/default.aspx");
        }
    }
    

    Esta página permite crear usuarios y asignarlos a una función.

El paso siguiente consiste en habilitar la autenticación de formularios, funciones y propiedades de perfil en el sitio web. Esto se lleva a cabo con parámetros de configuración en el archivo Web.config.

Para configurar la autenticación, las funciones y las propiedades de perfil

  1. Abra el archivo Web.config del sitio web.

  2. En el grupo system.web, cambie la autenticación predeterminada de Windows a formularios como se muestra en el ejemplo siguiente:

    <authentication mode="Forms" />
    
  3. En el grupo system.web, configure el servicio de funciones; para ello, agregue el elemento roleManager, como se muestra en el ejemplo siguiente:

    <roleManager enabled="true"/>
    
  4. En el grupo system.web, configure el servicio de perfil en la sección profile y su elemento properties como se muestra en el ejemplo siguiente:

    <profile enabled="true">
      <properties>
        <add name="FirstName"   type="String"/>
        <add name="LastName"    type="String"/>
        <add name="EmployeeId"  type="String"/>
      </properties>
    </profile>
    

    Esta configuración de perfil define tres propiedades que se administrarán en el servicio de perfil de ASP.NET. En tiempo de ejecución, ASP.NET creará dinámicamente una clase de tipo ProfileCommon que contenga estas propiedades.

    En el siguiente ejemplo se muestra una parte del archivo Web.config con todos los cambios necesarios.

    <system.web>
    <!-- Other settings. -->
    <authentication mode="Forms" />
    <roleManager enabled="true"/>
    <profile enabled="true">
      <properties>
        <add name="FirstName"   type="String"/>
        <add name="LastName"    type="String"/>
        <add name="EmployeeId"  type="String"/>
      </properties>
    </profile>
    </system.web>
    

Ahora puede crear información de usuario que usará más adelante para el inicio de sesión.

Para crear usuarios y asignar información de perfil

  1. En el Explorador de soluciones, seleccione la página Default.aspx y, a continuación, presione CTRL+F5 para ejecutar la página.

    La página se muestra en el explorador con la siguiente dirección URL:

    https://localhost:8080/WcfApplicationServices/Default.aspx
    
  2. Haga clic en New User.

    Se muestra la página CreateUser.aspx.

  3. Cree algunos usuarios y asígnelos a las funciones predefinidas. Para ello, escriba las credenciales de usuario y, a continuación, haga clic en Create User.

    Anote los nombres de usuario y las contraseñas que haya creado. Los necesitará para asignar o cambiar la información de perfil de los usuarios.

    Por ejemplo, cree un usuario cuyo nombre de usuario sea "joeA" y active la casilla Administrador para que dicho usuario sea miembro de la función Administrators. Cree un segundo usuario con el nombre de usuario "joeNA" y no active la casilla Administrador. El usuario joeNA será miembro de la función Friends, pero no así de Administrators. Las funciones Friends y Administrators se crean mediante código agregado anteriormente al método Application_Start en el archivo Global.asax.

    Una vez creado un usuario, se le redirigirá a la página Default.aspx.

  4. En la página Default.aspx, haga clic en Login.

    Se muestra la página Login.aspx.

  5. Inicie sesión con las credenciales de uno de los usuarios creados anteriormente.

    Si el inicio de sesión es correcto, se le redirige a la página Default.aspx.

  6. Haga clic en Profile Information.

    Se muestra la página Profile.aspx.

  7. Escriba o actualice la información de perfil del usuario registrado; para ello, escriba el nombre, el apellido y el número de identificación.

  8. Haga clic en Update Profile Data.

  9. Haga clic en Read Profile Information.

    Se muestra la información que acaba de especificar. Este paso permite asegurarse de si las propiedades de perfil funcionan correctamente.

Ha terminado de crear los usuarios y la información de perfil. Ahora hará que esta información esté disponible en las aplicaciones cliente.

Asignar y configurar servicios de aplicación

Ahora puede exponer la información del usuario que ha creado mediante los servicios de la aplicación ASP.NET. Antes de poder tener acceso a la información de credencial y perfil del usuario en el cliente, debe crear archivos de asignación (.svc) que señalen a los servicios de aplicación. Esto hace que los servicios estén disponibles para cualquier aplicación que se ejecute en una plataforma que pueda enviar y recibir mensajes SOAP. También debe configurar el sitio web para que los servicios de aplicación se expongan en la red.

Para crear archivos de asignación de los servicios de aplicación

  1. Agregue un archivo de servicio WCF (.svc) al sitio web y denomínelo MyAuthenSvcWra.svc.

  2. Reemplace la directiva @ ServiceHost existente con la siguiente, que hace referencia a la clase System.Web.ApplicationServices.AuthenticationService:

    <%@ ServiceHost Language="VB"
      Service="System.Web.ApplicationServices.AuthenticationService" 
      Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" 
      Debug="true" %>
    
    <%@ ServiceHost Language="C#"
      Service="System.Web.ApplicationServices.AuthenticationService" 
      Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" 
      Debug="true" %>
    

    Este servicio de ejemplo no implementa un servicio de autenticación personalizado, sino que se llama a la clase System.Web.ApplicationServices.AuthenticationService integrada.

  3. Elimine los archivos de interfaz y de clase creados en el directorio App_Code (App_Code\MyAuthenSvcWrap y App_Code\IMyAuthenSvcWrap).

    Los archivos de interfaz y de clase se crearon al agregar al proyecto el archivo.svc. No necesita estos archivos, puesto que está usando el servicio System.Web.ApplicationServices.AuthenticationService y no implementando un servicio personalizado.

  4. Agregue otro archivo de servicio WCF (.svc) al sitio web y denomínelo MyRoleSvcWrap.svc.

  5. Abra el archivo MyRoleSvcWrap.svc y reemplace su contenido con la directiva @ ServiceHost siguiente, que crea una referencia a la clase System.Web.ApplicationServices.RoleService:

    <%@ ServiceHost Language="VB" 
       Service="System.Web.ApplicationServices.RoleService" 
       Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Language="C#" 
      Service="System.Web.ApplicationServices.RoleService" 
      Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
  6. En el directorio App_Code, elimine los archivos de interfaz y de clase del servicio MyRoleSvcWrap.

  7. Agregue otro archivo de servicio WCF (.svc) al sitio web y denomínelo MyProfileSvcWrap.svc.

  8. Abra el archivo MyProfileSvcWrap.svc y reemplace su contenido con la directiva siguiente, que crea una referencia a la clase System.Web.ApplicationServices.ProfileService:

    <%@ ServiceHost Language="VB"
      Service="System.Web.ApplicationServices.ProfileService" 
      Factory ="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
    <%@ ServiceHost Language="C#"
    Service="System.Web.ApplicationServices.ProfileService" 
    
    Factory ="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
    
  9. En el directorio App_Code, elimine los archivos de interfaz y de clase del servicio MyProfileSvcWrap.

  10. Guarde y cierre todos los archivos .svc.

Ahora puede configurar la aplicación web para exponer los servicios de aplicación.

Para configurar los servicios de aplicación

  1. Abra el archivo Web.config o cambie a él.

  2. Agregue una nueva sección system.web.extensions bajo la sección configSections.

  3. En el elemento scripting, habilite los servicios de aplicación a través de la sección webServices.

    En el ejemplo siguiente se muestra el elemento system.web.extensions finalizado.

    </configSections>
    
    <system.web.extensions>
      <scripting>
        <webServices>
          <authenticationService enabled="true"
           requireSSL = "false"/>
          <profileService
              enabled="true"
              readAccessProperties="FirstName,LastName,EmployeeId"/>
          <roleService enabled="true"/>
        </webServices>
      </scripting>
    </system.web.extensions>
    
      <appSettings/>
    
  4. Como elemento secundario de la sección system.serviceModel, agregue un elemento serviceHostingEnvironment y establezca su aspNetCompatibilityEnabled en true.

    En el ejemplo siguiente se muestra el elemento serviceHostingEnvironment finalizado.

    </runtime>
     <system.serviceModel>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    
  5. En el grupo system.serviceModel, configure los servicios de aplicación para que las aplicaciones cliente puedan tener acceso a ellos mediante el protocolo SOAP. Para ello, siga estos pasos:

    1. En el elemento system.serviceModel, busque el elemento <behaviors><serviceBehaviors><behavior> cuyo atributo de nombre es "MyAuthenSvcWrapBehavior".

    2. Cambie el valor del atributo name del elemento behavior de "MyAuthenSvcWrapBehavior" a "AppServiceBehaviors". En este tutorial, se configura la aplicación de forma que utilice el comportamiento de AppServiceBehaviors para los tres servicios.

    3. Elimine los elementos behavior cuyos nombres son "MyRoleSvcWrapBehavior" y "MyProfileSvcWrapBehavior" del elemento <system.serviceModel><behaviors><serviceBehaviors>.

    En el ejemplo siguiente se muestra la sección <system.serviceModel> finalizada.

    </runtime>
     <system.serviceModel>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      <behaviors>
       <serviceBehaviors>
        <behavior name="AppServiceBehaviors">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
       </serviceBehaviors>
      </behaviors>
    
  6. En el elemento <system.serviceModel><services><service> denominado "MyAuthenSvcWrapBehavior", cambie el valor del atributo behaviorConfiguration del elemento behavior de "MyAuthenSvcWrapBehavior" a "AppServiceBehaviors".

  7. Cambie el valor del atributo name de "MyAuthenSvcWrap" a "System.Web.ApplicationServices.AuthenticationService".

  8. Configure el elemento <service><endpoint> del siguiente modo:

    1. Elimine el atributo address.

    2. Cambie el valor del atributo binding de "wsHttpBinding" a "basicHttpBinding".

    3. Cambie el valor del atributo contract de "IMyAuthenSvcWrap" a "System.Web.ApplicationServices.AuthenticationService".

    4. Añada el atributo bindingNamespace y establézcalo en "https://asp.net/ApplicationServices/v200".

    5. Elimine el elemento identity secundario.

    En el ejemplo siguiente se muestra el marcado del elemento service de autenticación.

    <service
      behaviorConfiguration="AppServiceBehaviors" 
      name="System.Web.ApplicationServices.AuthenticationService">
        <endpoint binding="basicHttpBinding" 
      contract="System.Web.ApplicationServices.AuthenticationService"
          bindingNamespace="https://asp.net/ApplicationServices/v200"       
                   >
        </endpoint>
    </service>
    

    Para obtener más información, vea <service> (Elemento).

  9. Repita el paso 8 para el elemento MyAuthenSvcWrap.

    En el ejemplo siguiente se muestra el elemento system.serviceModel completo.

    <system.serviceModel>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
      <behaviors>
       <serviceBehaviors>
        <behavior name="AppServiceBehaviors">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
       </serviceBehaviors>
      </behaviors>
      <services>
        <service 
            behaviorConfiguration="AppServiceBehaviors" 
            name="System.Web.ApplicationServices.AuthenticationService">
          <endpoint  binding="basicHttpBinding" 
              contract="System.Web.ApplicationServices.AuthenticationService"
               bindingNamespace="https://asp.net/ApplicationServices/v200"       
                   />
        </service>
        <service 
            behaviorConfiguration="AppServiceBehaviors" 
            name="System.Web.ApplicationServices.RoleService">
          <endpoint  binding="basicHttpBinding" 
              contract="System.Web.ApplicationServices.RoleService"
              bindingNamespace="https://asp.net/ApplicationServices/v200"       
                   />
        </service>
        <service 
            behaviorConfiguration="AppServiceBehaviors" 
            name="System.Web.ApplicationServices.ProfileService">
          <endpoint  binding="basicHttpBinding"
              contract="System.Web.ApplicationServices.ProfileService"
              bindingNamespace="https://asp.net/ApplicationServices/v200"
                   />
        </service>
      </services>
     </system.serviceModel>
    </configuration>
    

Ahora puede ejecutar el sitio web para activar los servicios de autenticación que usará la aplicación cliente de Windows. Esto también permite comprobar que la infraestructura del servicio de aplicación funciona correctamente.

Para activar el sitio web y exponer los servicios de aplicación

  • En el Explorador de soluciones, haga clic con el botón secundario en el archivo MyAuthenSvcWrap.svc y, a continuación, haga clic en Ver en el explorador.

    Se invoca el servicio web y aparece una página en el explorador que proporciona instrucciones para probar el servicio. Tome nota de la dirección URL del servicio, porque la necesitará en los pasos siguientes para tener acceso al servicio desde la aplicación cliente.

    Nota:

    No cierre el explorador. Cuando usa el servidor de desarrollo de ASP.NET, el explorador debe seguir abierto para que los servicios de aplicación continúen activos.

Ha terminado de configurar los servicios de aplicación para que estén disponibles en la Web. El paso siguiente es invocar estos servicios desde una aplicación cliente.

Usar los servicios de aplicación

En esta sección se muestra cómo crear una aplicación cliente en forma de una aplicación de consola de Windows para tener acceso a los servicios de aplicación. Cualquier cliente que puede enviar y recibir mensajes en formato SOAP puede obtener acceso a los servicios de aplicación

Para crear la aplicación de consola de cliente, debe seguir estos pasos generales:

  • Cree la aplicación cliente.

  • Genere los archivos de proxy de servicios de aplicación y un archivo de configuración relacionado.

  • Agregue el proxy y los archivos de configuración generados a la aplicación cliente y compile la aplicación.

  • Llame a las operaciones del servicio de aplicación a través de los proxys generados.

    Nota:

    Si pasa datos de usuario confidenciales al servicio como credenciales de autenticación, utilice la capa de sockets seguros (SSL, con el protocolo HTTPS). Por ejemplo, en el ejemplo siguiente, se cambiaría el valor del atributo requireSSL del elemento authenticationService de "false" a "true". Para obtener más información, vea Transport Security y HTTP Security and ASP.NET Web Services en el sitio web de MSDN, y Configuring Secure Sockets Layer in IIS 7.0 en el sitio web de IIS.

Para crear una aplicación de consola de Windows

  1. En Visual Studio, en el menú Archivo, haga clic en Agregar y, a continuación, en Nuevo proyecto.

  2. Seleccione su lenguaje preferido y, a continuación, en Plantillas instaladas de Visual Studio, seleccione Aplicación de consola.

  3. Denomine la aplicación AppSvcClient, escriba una ubicación y, a continuación, haga clic en Aceptar.

    Visual Studio agrega el proyecto a la solución actual y abre el archivo de clase predeterminado.

  4. Haga clic con el botón secundario en el nombre de la aplicación de consola y haga clic en Agregar referencia.

  5. En el cuadro de diálogo Agregar referencia, haga clic en la ficha .NET, seleccione System.ServiceModel y System.Runtime.Serialization y, a continuación, haga clic en Aceptar.

    De esta forma agrega espacios de nombres al proyecto que incluyen las clases necesarias para utilizar las clases de proxy.

Generar clases de proxy e información de configuración para los servicios de aplicación

Ahora puede generar las clases de proxy y la información de configuración que permitirán a la aplicación de consola tener acceso a los servicios de aplicación desde la aplicación de consola AppSvcClient. Debe generar una clase de proxy y configuración por separado para cada servicio de aplicación.

Para generar clases de proxy para los servicios de aplicación

  1. En el menú Inicio de Windows, haga clic en Todos los programas, Microsoft Visual Studio 2008, Visual Studio Tools y, por último, en Símbolo del sistema de Visual Studio 2008.

    Nota:

    Si está ejecutando Microsoft Vista, ejecute este comando como administrador.

    Esto abre una ventana de comandos de Windows cuya configuración del entorno incluye una ruta de acceso a las herramientas de .NET Framework.

  2. En línea de comandos de Windows, cambie el directorio que contiene el archivo Program.cs o Module1.vb del proyecto AppSvcClient.

  3. Genere la clase de proxy del servicio de autenticación con la herramienta Svcutil.exe. En la línea de comandos de Windows que abrió en el paso 1, escriba el comando siguiente:

    svcutil https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"VB"
    
    svcutil https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"C#"
    
    Nota:

       El lenguaje predeterminado es C#. El marcador /language:"VB" solo es necesario para Visual Basic.

    El valor "localhost:8080" debe coincidir con la dirección URL que utilice cuando ejecute el sitio web desde este tutorial. Si usó un número de puerto diferente para el servidor de desarrollo de ASP.NET o si utiliza una asignación de puerto dinámica, asigne el valor adecuado. Si cambia el número de puerto, debe actualizar el archivo .config que genera la herramienta Svcutil.exe para coincidir con el nuevo número de puerto.

    El nombre del archivo .svc en el comando debe coincidir con el nombre que usó para crear el archivo .svc anteriormente en este tutorial. El nombre de archivo de la clase de proxy es arbitrario; en este ejemplo, el nombre de la clase de proxy coincide con el nombre del archivo .svc correspondiente.

  4. Cambie el nombre del archivo de configuración output.config que se generó con la herramienta de la utilidad del servicio a App.config.

  5. En el Explorador de soluciones, haga clic con el botón secundario en el nombre de la aplicación de consola, haga clic en Agregar, haga clic en Elemento existente, seleccione el archivo de clase de proxy AuthenticationService que generó y, a continuación, haga clic en Agregar.

  6. En el archivo de clase principal de la aplicación de consola, agregue el código siguiente para crear una prueba.

    Imports System.ServiceModel
    
    Module Module1
    
        Sub Main(ByVal args As String())
    
            If (args.Length <> 2) Then
                Console.WriteLine("missing args username password")
                Return
            End If
    
            Dim username As String = args(0)
            Dim password As String = args(1)
            Dim result As Boolean = False
            Dim customCredential As String = "Not Used by the default membership provider"
            Dim isPersistent As Boolean = True ' authentication ticket remains valid across sessions.
    
            'BasicHttpBinding and endpoint are provided in app.config file.
            Dim authService As New AuthenticationServiceClient()
    
            result = authService.Login(username, password, customCredential, isPersistent)
    
            If result Then
                Console.WriteLine("Welcome " + username + ". You have logged in.")
            Else
                Console.WriteLine("We could not validate your credentials.")
            End If
    
            Console.WriteLine("Enter any key to exit.")
            Console.Read()
    
        End Sub
    
    End Module
    
    using System;
    using System.Text;
    using System.ServiceModel;
    
    class Program {
    
        static void Main(string[] args) {
    
            if (args.Length < 1) {
                Console.WriteLine("missing args username password");
                return;
            }
    
            string username = args[0];
            string password = args[1];
            bool result = false;
    
            // BasicHttpBinding and endpoint are provided in app.config file
            AuthenticationServiceClient authService = new AuthenticationServiceClient();
            string customCredential = "Not Used by the default membership provider";
            bool isPersistent = true;  // authentication ticket remains valid across sessions.
    
            result = authService.Login(username, password, customCredential, isPersistent);
    
            if (result == true)
                Console.WriteLine("Welcome " + username + ". You have logged in.");
            else
                Console.WriteLine("Unable to login");
        }
    }
    

    El código permite pasar un nombre de usuario y una contraseña al servicio al ejecutarlo desde la aplicación de consola. Puede usar los valores de los usuarios y las contraseñas que creó anteriormente en el tutorial.

    La aplicación de prueba obtiene la información de enlace y extremo del archivo App.config.

  7. Pruebe el proyecto del siguiente modo:

    1. En Visual Studio, genere la solución.

    2. En la línea de comandos, cambie a la carpeta \bin\debug y ejecute AppSvcClient.exe. Pase un nombre de usuario y una contraseña en la línea de comandos.

    La aplicación de consola muestra un mensaje que indica que ha iniciado sesión.

  8. Genere la clase de proxy del servicio de perfil; para ello, copie el siguiente comando en la ventana Comandos de Windows:

    svcutil.exe https://localhost:8080/WcfApplicationServices/MyProfileSvcWrap.svc?wsdl /language:"VB" /config:app.config /mergeConfig
    
    svcutil.exe https://localhost:8080/WcfApplicationServices/MyProfileSvcWrap.svc?wsdl /language:"C#" /config:app.config /mergeConfig
    

    La opción /config:app.config designa el archivo App.config como archivo de configuración en lugar del archivo output.config, que es el predeterminado. La opción /mergeConfig especifica que la información de configuración generada en este paso debería combinarse con la información ya incluida en el archivo App.config en pasos anteriores.

  9. Genere la clase de proxy del servicio de autenticación; para ello, copie el siguiente comando en la ventana Comandos de Windows:

    svcutil.exe https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"VB" /config:app.config /mergeConfig
    
    svcutil.exe https://localhost:8080/WcfApplicationServices/MyAuthenSvcWrap.svc?wsdl /language:"C#" /config:app.config /mergeConfig
    
  10. Genere la clase de proxy del servicio de funciones; para ello, copie el siguiente comando en la ventana Comandos de Windows:

    svcutil.exe https://localhost:8080/WcfApplicationServices/MyRoleSvcWrap.svc?wsdl /language:"VB" /config:app.config /mergeConfig
    
    svcutil.exe https://localhost:8080/WcfApplicationServices/MyRoleSvcWrap.svc?wsdl  /language:"C#" /config:app.config /mergeConfig
    
  11. En el Explorador de soluciones, haga clic con el botón secundario en el nombre de la aplicación de consola, haga clic en Agregar, en Elemento existente, seleccione los archivos de clase de proxy que generó y, a continuación, haga clic en Agregar.

    Las clases de proxy se encuentran en la misma carpeta que el archivo App.config y se denominan AuthenticationService, ProfileService y RoleService.

  12. Reemplace el código en la clase Program por el siguiente código:

    Imports System
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.ServiceModel
    Imports System.ServiceModel.Activation
    Imports System.ServiceModel.Channels
    Imports System.ComponentModel
    Imports System.Web
    Imports System.Net
    
    Module Module1
    
        Class MyServiceTst
    
            Dim _host As String
    
            Public Property Host() As String
                Get
                    Return _host
                End Get
                Set(ByVal value As String)
                    _host = value
                End Set
            End Property
    
            Function GetCookies(ByVal oc As OperationContext) As CookieContainer
                Dim httpResponseProperty As HttpResponseMessageProperty = DirectCast(oc.IncomingMessageProperties(HttpResponseMessageProperty.Name), HttpResponseMessageProperty)
                If (httpResponseProperty.Equals(Nothing) = False) Then
                    Dim cookieContainer As New CookieContainer()
                    Dim header As String = httpResponseProperty.Headers(HttpResponseHeader.SetCookie)
    
                    If header <> Nothing Then
                        cookieContainer.SetCookies(New Uri("http://someuri.tld"), header)
                    End If
                    Return cookieContainer
                End If
                Return Nothing
            End Function
    
            Sub SetCookies(ByVal oc As OperationContext, ByVal cookieContainer As CookieContainer)
                Dim httpRequestProperty = New HttpRequestMessageProperty()
                httpRequestProperty = Nothing
                If oc.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name) Then
                    httpRequestProperty = TryCast(oc.OutgoingMessageProperties(HttpRequestMessageProperty.Name), HttpRequestMessageProperty)
                End If
                If httpRequestProperty Is Nothing Then
                    httpRequestProperty = New HttpRequestMessageProperty()
                    oc.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequestProperty)
                End If
                httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(New Uri("http://someuri.tld")))
            End Sub
    
            Sub GetUserRoles(ByVal cookieContainer As CookieContainer)
                Dim roleSvc As New RoleServiceClient()
    
                Using New OperationContextScope(DirectCast(roleSvc.InnerChannel, IContextChannel))
                    SetCookies(OperationContext.Current, cookieContainer)
                    Dim roles As String() = roleSvc.GetRolesForCurrentUser()
                    If roles.Length = 0 Then
                        Console.WriteLine("User does not belong to any role.")
                    Else
                        Dim userRoles As String = ""
                        Dim i As Integer = 0
                        While i < roles.Length
                            userRoles += roles(i) + " "
                            Global.System.Math.Max(Global.System.Threading.Interlocked.Increment(i), i - 1)
                        End While
                        Console.WriteLine("User's roles: " + userRoles)
    
                    End If
                End Using
            End Sub
    
            Sub GetProfileInfo(ByVal cookieContainer As CookieContainer)
                Dim profileSvc As New ProfileServiceClient()
    
                Using New OperationContextScope(DirectCast(profileSvc.InnerChannel, IContextChannel))
                    SetCookies(OperationContext.Current, cookieContainer)
                    Dim profileData As Dictionary(Of String, Object) = profileSvc.GetPropertiesForCurrentUser(New String() {"FirstName", "LastName", "EmployeeId"}, True)
    
                    Console.WriteLine("FirstName: " + profileData("FirstName"))
                    Console.WriteLine("LastName: " + profileData("LastName"))
                    Console.WriteLine("EmployeeId: " + profileData("EmployeeId"))
                End Using
            End Sub
    
            Public Function strEndPtAddr(ByVal service As String) As String
                Dim endPtAddr As String = "http://" + Host + "/WcfApplicationServices/" + service + ".svc?wsdl"
    
                Return endPtAddr
            End Function
    
            Sub Init(ByVal args As String())
    
                If (args.Length = 3) Then  'The host address was passed in , use that.
                    Host = args(2)
                Else
                    Host = "localhost:8080"  
                End If
    
                Dim username As String = args(0)
                Dim password As String = args(1)
                Dim result As Boolean
                Dim binding As BasicHttpBinding = New BasicHttpBinding()
                Dim endPtAddr As String = strEndPtAddr("MyAuthenSvcWrap")
    
                Console.WriteLine("Attempting to connect as username = " + username + vbNewLine _
                  + "password length = " + password.Length.ToString() + vbNewLine _
                  + " on server " + Host + vbNewLine _
                  + "End point address: " + endPtAddr _
                  )
                ' BasicHttpBinding and endpoint are explicitly passed and ignored
                ' in app.config file.
    
                Dim authService As AuthenticationServiceClient = New AuthenticationServiceClient(binding, _
                                                      New EndpointAddress(endPtAddr))
    
                Dim cookieContainer As CookieContainer = Nothing
                Dim customCredential As String = "Not Used by the default membership provider"
                Dim isPersistent As Boolean = True   ' authentication ticket remains valid across sessions.
    
                Using New OperationContextScope(authService.InnerChannel)
                    Try
                        result = authService.Login(username, password, customCredential, isPersistent)
                        cookieContainer = GetCookies(OperationContext.Current)
                    Catch enf As EndpointNotFoundException
                        Console.WriteLine(enf.Message)
                        Return
                    End Try
    
    
                End Using
    
                If result Then
                    Console.WriteLine("Welcome " + username + ". You have logged in.")
    
                    GetProfileInfo(cookieContainer)
                    GetUserRoles(cookieContainer)
                Else
                    Console.WriteLine("We could not validate your credentials.")
                End If
    
    
            End Sub
        End Class
    
    
    
        Sub Main(ByVal args As String())
    
            If (args.Length < 1) Then
                Console.WriteLine("missing args username password")
                Return
            End If
    
            Dim mst As MyServiceTst = New MyServiceTst()
            mst.Init(args)
    
    
            Console.WriteLine("Enter any key to exit.")
            Console.Read()
    
        End Sub
    
    End Module
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Channels;
    using System.ComponentModel;
    using System.Web;
    using System.Net;
    
    
    class MyServiceTst {
    
        string Host { get; set; }      
    
        CookieContainer GetCookies(OperationContext oc) {
            HttpResponseMessageProperty httpResponseProperty =
                (HttpResponseMessageProperty)oc.IncomingMessageProperties[HttpResponseMessageProperty.Name];
            if (httpResponseProperty != null) {
                CookieContainer cookieContainer = new CookieContainer();
                string header = httpResponseProperty.Headers[HttpResponseHeader.SetCookie];
    
                if (header != null) {
                    cookieContainer.SetCookies(new Uri(@"http://someuri.tld"), header);
                }
                return cookieContainer;
            }
            return null;
        }
    
        void SetCookies(OperationContext oc, CookieContainer cookieContainer) {
    
            HttpRequestMessageProperty httpRequestProperty = null;
            if (oc.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) {
                httpRequestProperty =
                    oc.OutgoingMessageProperties[HttpRequestMessageProperty.Name]
                    as HttpRequestMessageProperty;
            }
    
            if (httpRequestProperty == null) {
                httpRequestProperty = new HttpRequestMessageProperty();
                oc.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name,
                    httpRequestProperty);
            }
            httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie,
                cookieContainer.GetCookieHeader(new Uri(@"http://someuri.tld")));
        }
    
    
        void GetUserRoles(CookieContainer cookieContainer) {
    
            string endPtAddr = strEndPtAddr("MyRoleSvcWrap");
    
            RoleServiceClient roleSvc = new RoleServiceClient(new BasicHttpBinding(),
                 new EndpointAddress(endPtAddr));
    
            using (new OperationContextScope((IContextChannel)roleSvc.InnerChannel)) {
                SetCookies(OperationContext.Current, cookieContainer);
                string[] roles = roleSvc.GetRolesForCurrentUser();
                if (roles.Length == 0) {
                    Console.WriteLine("User does not belong to any role.");
                } else {
                    string userRoles = "";
                    for (int i = 0; i < roles.Length; i++) {
                        userRoles += roles[i] + " ";
                    }
                    Console.WriteLine("User's roles: " + userRoles);
                }
    
            }
        }
    
        void GetProfileInfo(CookieContainer cookieContainer) {
    
            string endPtAddr = strEndPtAddr("MyProfileSvcWrap");
    
            ProfileServiceClient profileSvc = new ProfileServiceClient(new BasicHttpBinding(),
                 new EndpointAddress(endPtAddr));
    
            string[] strProfileProps = new string[] { "FirstName", "LastName", "EmployeeId" };
    
            using (new OperationContextScope((IContextChannel)profileSvc.InnerChannel)) {
                SetCookies(OperationContext.Current, cookieContainer);
                Dictionary<string, object> profileData =
                    profileSvc.GetPropertiesForCurrentUser(strProfileProps, true);
    
                foreach (string sProp in strProfileProps)
                    Console.WriteLine(sProp + ": " + profileData[sProp]);
    
            }
        }
    
        public string strEndPtAddr(string service) {
    
            string endPtAddr = @"http://" + Host + "/WcfApplicationServices/"
                + service + ".svc?wsdl";
    
            return endPtAddr;
        }
    
        public void Init(string[] args) {
    
            if (args.Length == 3)   // The host address was passed in , use that
                Host = args[2];
            else
                Host = "localhost:8080";  
    
            string username = args[0];
            string password = args[1];
            bool result = false;
            BasicHttpBinding binding = new BasicHttpBinding();
            string endPtAddr = strEndPtAddr("MyAuthenSvcWrap");
    
            Console.WriteLine("Attempting to connect as username = " + username
                + "\n password length = " + password.Length.ToString()
                + "\n on server " + Host + "\n"
                + "\n" + endPtAddr
            );
    
            // BasicHttpBinding and endpoint are explicitly passed and ignored
            // in app.config file
    
            AuthenticationServiceClient authService = new AuthenticationServiceClient(binding,
                                                         new EndpointAddress(endPtAddr));
    
            CookieContainer cookieContainer;
            string customCredential = "Not Used by the default membership provider";
            bool isPersistent = true;  // authentication ticket remains valid across sessions.
    
            using (new OperationContextScope(authService.InnerChannel)) {
                try {
                    result = authService.Login(username, password,
                                                 customCredential, isPersistent);
                    cookieContainer = GetCookies(OperationContext.Current);
                } catch (EndpointNotFoundException enfe) {
                    Console.WriteLine(enfe.Message);
                    if (enfe.InnerException != null && enfe.InnerException.Message != null)
                        Console.WriteLine(enfe.InnerException.Message);
                    return;
                }
            }
    
            if (result) {
                Console.WriteLine("Welcome " + username + ". You have logged in.");
    
                GetUserRoles(cookieContainer);
                GetProfileInfo(cookieContainer);
            } else {
                Console.WriteLine("We could not validate your credentials.");
            }
    
        }
    }
    
    class Program {
    
        static void Main(string[] args) {
    
            if (args.Length < 1) {
                Console.WriteLine("missing args username password [host]");
                return;
            }
            MyServiceTst mst = new MyServiceTst();
            mst.Init(args);
    
            Console.WriteLine("Enter any key to exit.");
            // Console.Read();
        }
    
    }
    
    
  13. Genere el proyecto.

Acceso a los servicios de aplicación

Ahora puede ejecutar la aplicación cliente y usar los servicios de aplicación que ha expuesto como parte del sitio web.

Para ejecutar la aplicación de Windows

  1. En el símbolo del sistema de Windows, cambie al directorio de la aplicación de consola.

  2. Escriba el siguiente comando con el nombre de usuario y la contraseña de uno de los usuarios que creó anteriormente en el tutorial.

    AppSvcClient.exe <userName> <password>

    Si escribe las credenciales correctas, se autenticará y obtendrá la información de funciones y perfil asociada al usuario que ha iniciado sesión.

Pasos siguientes

En este tutorial se han mostrado los principios básicos del acceso a los servicios de aplicación ASP.NET desde una aplicación cliente que puede enviar y recibir mensajes en formato SOAP.

Es posible que desee probar otras características del servicio de aplicación. Las sugerencias para la exploración adicional incluyen lo siguiente:

Para obtener información general sobre los servicios web, puede interesarle:

  • Descripción del procesamiento que se produce cuando se realiza una llamada a un servicio web. Para obtener más información, vea Anatomía de la duración de un servicio web XML.

  • Descripción del uso de los servicios web. Para obtener más información, vea Escenarios del servicio web XML.

  • Obtenga más información sobre los servicios de la aplicación ASP.NET. Para obtener más información, vea AuthenticationServiceLogin().

Vea también

Tareas

Cómo: Habilitar el servicio de autenticación de WCF

Cómo: Habilitar el servicio de funciones de WCF

Cómo: Habilitar el servicio de perfiles de WCF

Conceptos

Definición de las propiedades de perfil ASP.NET

Información general sobre los servicios de aplicación ASP.NET