Compartir a través de


Usar información de funciones con AJAX en ASP.NET

Actualización: noviembre 2007

Las funciones de ASP.NET permiten agrupar usuarios autenticados y tratar cada grupo como una unidad. Esto puede ser útil para cualquier acción que se aplique a varios usuarios, como habilitar o denegar el acceso a recursos del servidor.

El servicio de función de aplicación de Microsoft AJAX Library permite tener acceso a las funciones de un usuario autenticado desde script de cliente en una aplicación web ASP.NET habilitada para AJAX. Puede usar el servicio de función de aplicación de Microsoft AJAX Library para realizar tareas basadas en función mediante script de cliente. Cuando se ejecuta la página, puede llamar a la clase de proxy RoleService de ECMAScript (JavaScript), que el servicio de función de aplicación genera automáticamente y descarga al explorador.

En este tema se muestra cómo llamar al servicio de función de aplicación ASP.NET desde el explorador con JavaScript.

Habilitar el servicio de función

Para usar el servicio de función desde script de cliente, debe habilitarlo mediante el elemento siguiente en el archivo Web.config de la aplicación.

<system.web.extensions>
  <scripting>
    <webServices
      < rolesService enabled="true" />
    </webServices
  </scripting>
</system.web.extensions>

Para obtener más información, consulte Cómo: Configurar servicios de ASP.NET en ASP.NET AJAX.

Código de

El ejemplo siguiente muestra cómo usar el servicio de función desde script de cliente.

Nota:

Para ejecutar el ejemplo, compruebe que hay por lo menos un usuario definido en la base de datos de pertenencia de la aplicación. Para obtener información sobre cómo crear un usuario en la base de datos de SQL Server Express Edition predeterminada, vea Utilizar la autenticación de formularios con AJAX en ASP.NET.

<%@ Page Language="VB"  Title="Using Roles Service" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >

    <title>Using Roles Service</title>
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>

<script language="javascript" type="text/jscript">



</script>


</head>
<body>

    <form id="form1" >

        <h2>Access Authenticated User's Roles</h2>
        Using the Sys.Services.RoleService client type to obtain roles information.

        <p>
            You must be authenticated to access roles information. <br /> 
            Refer to the Forms Authentication example.
        </p>
    
       <asp:ScriptManager  ID="ScriptManagerId">
            <Scripts>
                <asp:ScriptReference Path="Roles.js" />
            </Scripts>
        </asp:ScriptManager>

        <hr />

        <table>
            <tr>
                <td align="left">User's roles: </td>
                <td align="left"> 
                    <input type="button" id="UserRoles" 
                           onclick="ReadUserRoles(); return false;" 
                           value="UserRoles" />
                </td>
            </tr>
            <tr>
                <td align="left">Is User in Administrators Role?: </td>
                <td align="left" >
                    <input type="button" id="UserInRole" 
                           onclick="UserIsInRole('Administrators'); return false;" 
                           value="Check Role" /></td>
            </tr>
            
            <tr>
                <td align="left">Role Service path: </td>
                <td align="left">
                    <input type="button" id="ServicePathId" 
                           onclick="GetRoleServicePath(); return false;" 
                           value="Role Service Path" /></td>
            </tr>
            <tr>
                <td align="left">Role Service timeout: </td>
                <td align="left">
                    <input type="button" id="ServiceTimeoutId" 
                           onclick="GetRoleServiceTimeout(); return false;" 
                           value="Role Service Timeout" /></td>
            </tr>
                
        </table>              

    </form>

    <div id="placeHolder" ></div>
</body>

</html>
<%@ Page Language="C#"  Title="Using Roles Service" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >

    <title>Using Roles Service</title>
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>

<script language="javascript" type="text/jscript">



</script>


</head>
<body>

    <form id="form1" >

        <h2>Access Authenticated User's Roles</h2>
        Using the Sys.Services.RoleService client type to obtain roles information.

        <p>
            You must be authenticated to access roles information. <br /> 
            Refer to the Forms Authentication example.
        </p>
    
       <asp:ScriptManager  ID="ScriptManagerId">
            <Scripts>
                <asp:ScriptReference Path="Roles.js" />
            </Scripts>
        </asp:ScriptManager>

        <hr />

        <table>
            <tr>
                <td align="left">User's roles: </td>
                <td align="left"> 
                    <input type="button" id="UserRoles" 
                           onclick="ReadUserRoles(); return false;" 
                           value="UserRoles" />
                </td>
            </tr>
            <tr>
                <td align="left">Is User in Administrators Role?: </td>
                <td align="left" >
                    <input type="button" id="UserInRole" 
                           onclick="UserIsInRole('Administrators'); return false;" 
                           value="Check Role" /></td>
            </tr>
            
            <tr>
                <td align="left">Role Service path: </td>
                <td align="left">
                    <input type="button" id="ServicePathId" 
                           onclick="GetRoleServicePath(); return false;" 
                           value="Role Service Path" /></td>
            </tr>
            <tr>
                <td align="left">Role Service timeout: </td>
                <td align="left">
                    <input type="button" id="ServiceTimeoutId" 
                           onclick="GetRoleServiceTimeout(); return false;" 
                           value="Role Service Timeout" /></td>
            </tr>
                
        </table>              

    </form>

    <div id="placeHolder" ></div>
</body>

</html>
var roleProxy;
var roles;

// This function creates the role proxy and 
// sets its default callback functions.
function pageLoad()
{
    // Create role service proxy.
    roleProxy = Sys.Services.RoleService;

    // Set the default failed callback function.
    DefaultFailedCallBack();

    // Set the default load completed callback function.
    DefaultLoadCompletedCallBack()

}


// This function sets and gets the role service
// default failed callback function.
function DefaultFailedCallBack()
{
     // Set default failed callback function.
    roleProxy.set_defaultFailedCallback(FailedCallback);

    // Get the default callback function. 
    var failedCallBack =     
        roleProxy.get_defaultFailedCallback();

    alert(failedCallBack); 
}



// This function sets and gets the role service
// default load completed callback function.
function DefaultLoadCompletedCallBack()
{
    // Set the default callback function.
    roleProxy.set_defaultLoadCompletedCallback(LoadCompletedCallback);

    // Get the default callback function. 
    var loadCompletedCallBack =     
        roleProxy.get_defaultLoadCompletedCallback();

    alert(loadCompletedCallBack);
}


// This function checks if the currently
// authenticated user belongs to the
// passed role. 
function UserIsInRole(role) 
{
    DisplayInformation("");
    var isUserInRole = roleProxy.isUserInRole(role);
    DisplayInformation("The user is in the " + role + 
        " role: " + isUserInRole);   
}


// This function gets the role service path.
function GetRoleServicePath()
{
    // Get the role service path.
    var roleServicePath = 
        Sys.Services.RoleService.get_path();
    if (roleServicePath == "")
    {
        DisplayInformation(
            "The role service path is the default value.");
    }
}


// This function gets the roles of the
// currently authenticated user. 
function ReadUserRoles() 
{
    // Clear the feedback output.
    DisplayInformation("");

    // You must load the user's roles 
    // first before you can use them.
    roleProxy.load();

    // Read the user's roles. 
    roles = roleProxy.get_roles();

}


// This function gets the role service timeout.
function GetRoleServiceTimeout()
{
    // Get the role service path.
    var roleServiceTimeout = 
        Sys.Services.RoleService.get_timeout();

    DisplayInformation(
            "Role service timeout: " + roleServiceTimeout);

}


// This is the callback function
// called if the role service load function
// completed.
function LoadCompletedCallback(roles) 
{  
    // Read the user's roles loaded
    // before.
    roles.sort();
    for(var i = 0; i < roles.length; i++) 
    {
        var roleInfo = "Role: " + roles[i];
        DisplayInformation(roleInfo);
    }       
}

// This is the callback function
// called if the role service fails.
function FailedCallback(error) 
{
    DisplayInformation("Error: " + error.get_message());   
}

// This function displays user's 
// feedback information.
function DisplayInformation(text)
{
    document.getElementById('placeHolder').innerHTML = 
    "<br/>"+ text;
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Vea también

Tareas

Cómo: Configurar servicios de ASP.NET en ASP.NET AJAX

Conceptos

Usar servicios web en ASP.NET para AJAX

Llamar a servicios web desde script de cliente

Utilizar la autenticación de formularios con AJAX en ASP.NET

Usar información de perfiles con AJAX en ASP.NET

Sys.Services.AuthenticationService (Clase)

Sys.Services.ProfileService (Clase)

Sys.Services.RoleService (clase)