Compartilhar via


Expondo Serviços Web a Script Cliente

A funcionalidade de AJAX do ASP.NET permite a você chamar serviços ASP.NET da Web (arquivos .asmx) a partir do navegador usando script cliente.Isso aumenta a experiência do usuário para o aplicativo da Web.A página pode chamar métodos com base no servidor sem uma postagem e atualizar a página inteira, porque apenas os dados são transferidos entre o navegador e o servidor Web.

Este tópico descreve como disponibilizar um serviço Web para JavaScript executado no navegador.

ASP.NET cria automaticamente as classes de proxy JavaScript para serviços da Web.Classes de proxy são derivadas da classe Sys.Net.WebServiceProxy.Você pode chamar um método de serviço Web chamando o método correspondente da classe de proxy JavaScript.Para obter mais informações, consulte Chamando Serviços da Web de Scripts Clientes.

Tornando Serviços da Web Acessível a partir de Script

Para um serviço Web ser acessado a partir de script, ele deve ser um serviço Web .asmx cujo serviço de classe Web é qualificado com o atributo ScriptServiceAttribute.Métodos individuais a serem chamados a partir de script devem ser qualificados com o atributo WebMethodAttribute.

O exemplo a seguir mostra esses atributos no código de serviço Web.

[ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string EchoInput(String input)
    {
        // Method code goes here.
    }
}

<ScriptService> _
Public Class SimpleWebService
        Inherits System.Web.Services.WebService
    <WebMethod> _
    Public Function EchoInput(ByVal input As String) As String
        ' Method code goes here.
    End Function
End Class

Para habilitar chamadas a serviços Web a partir de script, você deve registrar o manipulador HTTP ScriptHandlerFactory no arquivo web.config do aplicativo.O manipulador processa chamadas feitas a partir de script para serviços .asmx da Web.O exemplo a seguir mostra o elemento web.config para adição do manipulador.

Observação:

T eles serão definições de configuração são já parte do Web.config arquivo modelo para qualquer novo Habilitado para AJAX Sites que você criar em Microsoft Visual Studio 2005.

<system.web>
  <httpHandlers>
    <remove verb="*" path="*.asmx"/> 
    <add verb="*" path="*.asmx" 
      type="System.Web.Script.Services.ScriptHandlerFactory"
       validate="false"/>
  </httpHandlers>
<system.web>

Para chamadas de serviço Web que não são emitidas de clientes ASP.NET com script AJAX habilitado, o manipulador ScriptHandlerFactory delega a chamada para o manipulador padrão, que usa SOAP em vez do formato JSON.A delegação é executada automaticamente e não é necessário executar qualquer ação, a menos que se deseje desativar o uso de protocolo SOAP para os serviços da Web.Nesse caso, insira a seguinte configuração no arquivo web.config.

<system.web>
  <webServices>    <protocols>      <clear/>    </protocols>  </webServices>
</system.web>

Expondo Serviços da Web ao Script de Cliente em uma Página da Web do ASP.NET

Para ativar um serviço .asmx da Web a ser chamado de script cliente em um página ASP.NET da Web, adicione um controle ScriptManager à página.Você fazer referência ao serviço Web adicionando um elemento filho asp:ServiceReference ao controle ScriptManager e, em seguida, controlando e configurando o atributo path de referência do servidor para a URL de serviço Web.O objeto ServiceReference instrui o ASP.NET para gerar uma classe de proxy JavaScript para chamar o serviço Web especificado a partir do script cliente.

O exemplo a seguir mostra como ativar um serviço Web chamado SimpleWebService.asmx a ser chamado a partir de script em um página da Web do ASP.NET.

<asp:ScriptManager  ID="scriptManager">
  <Services>
    <asp:ServiceReference
       path="~/WebServices/SimpleWebService.asmx" />
  </Services>
</asp:ScriptManager>

O objeto ServiceReference pode fazer referência um serviço Web somente no mesmo domínio como a página.O caminho do serviço Web pode ser relativo, relativo ao aplicativo, relativo ao domínio ou absoluto.Para caminhos absolutos, você deve se certificar que o caminho está no mesmo domínio.

Quando uma página que contém este controle ScriptManager é processada, a página cria uma classe de proxy JavaScript para o serviço Web SimpleWebService.asmx.A classe de proxy tem métodos que correspondem aos métodos da Web no serviço de SimpleWebService.asmx.A página também contém classes de proxy JavaScript que correspondem aos tipos de dados do servidor que são usados como parâmetros de entrada ou retornam valores para os métodos de serviço Web.Isso permite que você escreva script de cliente que inicializa esses parâmetros e o passe para chamada de método.

A propriedade InlineScript do objeto ServiceReference especifica como a classe de proxy JavaScript está incluída na página.Se InlineScript estiver configurado para false (padrão), o script de proxy é obtido fazendo uma solicitação separada.Essa opção é melhor quando várias páginas fazem referência ao mesmo serviço e quando o cache do navegador está ativado.

Se InlineScript estiver definida como true, o script de classe de proxy é incluído como um bloco de script embutido na página.Isso pode melhorar o desempenho reduzindo o número de solicitações de rede.Isso é especialmente verdadeiro se houver muitas referências de serviço na página e outras páginas não fizerem referência ao mesmo serviço.Se InlineScript estiver definida como true, você deve usar um caminho relativo.Se o caminho for relativo ao domínio, ele deve se referir ao mesmo aplicativo da Web.

Os exemplos a seguir mostram um serviço Web simples que é chamado de script que exibe a entrada do usuário e retorna a hora atual do servidor.O exemplo a seguir mostra a página que faz chamadas de serviço por script de cliente.

<%@ Page Language="VB" %>

<!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" >
        <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

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

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.  
            function EchoUserInput()
            {
                var echoElem = document.getElementById("EnteredValue");
                Samples.AspNet.SimpleWebService.EchoInput(echoElem.value,
                    SucceededCallback);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function SucceededCallback(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" >
         <asp:ScriptManager  ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="SimpleWebService_VB.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Simple Web Service</h2>
                    <p>Calling a simple service that echoes the user's input and 
                        returns the current server time.</p>
                    <input id="EnteredValue" type="text" />
                    <input id="EchoButton" type="button" 
                        value="Echo" onclick="EchoUserInput()" />
            </div>
        </form>

        <hr/>

        <div>
            <span id="Results"></span>
        </div>   

    </body>

</html>
<%@ Page Language="C#" %>

<!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" >
        <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

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

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.  
            function EchoUserInput()
            {
                var echoElem = document.getElementById("EnteredValue");
                Samples.AspNet.SimpleWebService.EchoInput(echoElem.value,
                    SucceededCallback);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function SucceededCallback(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" >
         <asp:ScriptManager  ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="SimpleWebService.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Simple Web Service</h2>
                    <p>Calling a simple service that echoes the user's input and 
                        returns the current server time.</p>
                    <input id="EnteredValue" type="text" />
                    <input id="EchoButton" type="button" 
                        value="Echo" onclick="EchoUserInput()" />
            </div>
        </form>

        <hr/>

        <div>
            <span id="Results"></span>
        </div>   

    </body>

</html>

O exemplo a seguir mostra o serviço que é chamado através de script de cliente.

<%@ WebService Language="VB" Class="Samples.AspNet.SimpleWebService" %>

Imports System.Web
Imports System.Web.Services
Imports System.Xml
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

Namespace Samples.AspNet

    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <ScriptService()> _
    Public Class SimpleWebService
    Inherits System.Web.Services.WebService

    <WebMethod()>  _
    Public Function EchoInput(ByVal input As String) As String 
        Dim inputString As String = Server.HtmlEncode(input)
        If Not String.IsNullOrEmpty(inputString) Then
                Return String.Format("You entered {0}. The " + _
                "current time is {1}.", inputString, DateTime.Now)
        Else
            Return "The input string was null or empty."
        End If

    End Function 'EchoInput
End Class 'SimpleWebService 

End Namespace
<%@ WebService Language="C#" Class="Samples.AspNet.SimpleWebService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Samples.AspNet
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class SimpleWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string EchoInput(String input)
        {
            string inputString = Server.HtmlEncode(input);
            if (!String.IsNullOrEmpty(inputString))
            {
                return String.Format("You entered {0}. The "
                  + "current time is {1}.", inputString, DateTime.Now);
            }
            else
            {
                return "The input string was null or empty.";
            }
        }

    }

}

Chamando Métodos Estáticos em uma Página da Web

Você pode adicionar métodos estáticos página a uma página ASP.NET e qualificá-los como métodos da Web.Você pode, em seguida, chamar esses métodos de script na página como se fossem parte de uma serviço Web, mas sem criar um arquivo .asmx separado.Para criar métodos da Web em uma página, importe o namespace System.Web.Services e adicione um atributo WebMethodAttribute a cada método estático que deseja expor.Os Métodos de página devem ser definidos na página que se está executando a chamada ao método da página.

Para poder chamar métodos estáticos de página como métodos da Web, você deve definir o atributo EnablePageMethods do controle ScriptManager como true.

Os exemplos a seguir mostram como chamar métodos de página estática do script cliente para gravar e ler valores de estado de sessão.O exemplo a seguir mostra os métodos de página.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Services" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<script >

    <WebMethod()> _
    Public Shared Function GetSessionValue(ByVal key As String) As String
        ' Get session state value.
        Return CStr(HttpContext.Current.Session(key))

    End Function 'GetSessionValue


    <WebMethod()> _
    Public Shared Function SetSessionValue(ByVal key As String, _
    ByVal value As String) As String
        ' Set session state value.
        HttpContext.Current.Session(key) = value
        Return CStr(HttpContext.Current.Session(key))

    End Function 'SetSessionValue

</script>

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

<head id="Head1" >

    <title>Using Page Methods with Session State</title>
    <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }
            .text { font: 8pt Trebuchet MS }
    </style>
</head>

<body>

    <h2>Using Page Methods with Session State</h2>

    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1" 
             EnablePageMethods="true">
            <Scripts>
                <asp:ScriptReference Path="PageMethod.js"/>
            </Scripts>
        </asp:ScriptManager>
    </form>

     <center>
         <table>
            <tr align="left">
                <td>Write current date and time in session state:</td>
                <td>
                    <input type="button" 
                        onclick="SetSessionValue('SessionValue', Date())" 
                        value="Write" />
                </td>
            </tr>
            <tr align="left">
                <td>Read current date and time from session state:</td>
                <td>         
                    <input type="button" 
                        onclick="GetSessionValue('SessionValue')" 
                        value="Read" />
                </td>
            </tr>
        </table>           
    </center>

    <hr/>

    <span style="background-color:Aqua" id="ResultId"></span>

</body>

</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<script >

    [WebMethod]
    // Get session state value.
    public static string GetSessionValue(string key)
    {
        return (string)HttpContext.Current.Session[key];
    }

    [WebMethod]
    // Set session state value.
    public static string SetSessionValue(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
        return (string)HttpContext.Current.Session[key];
    }

</script>

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

<head id="Head1" >

    <title>Using Page Methods with Session State</title>
    <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }
            .text { font: 8pt Trebuchet MS }
    </style>
</head>

<body>

    <h2>Using Page Methods with Session State</h2>

    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1" 
             EnablePageMethods="true">
            <Scripts>
                <asp:ScriptReference Path="PageMethod.js"/>
            </Scripts>
        </asp:ScriptManager>
    </form>

     <center>
         <table>
            <tr align="left">
                <td>Write current date and time in session state:</td>
                <td>
                    <input type="button" 
                        onclick="SetSessionValue('SessionValue', Date())" 
                        value="Write" />
                </td>
            </tr>
            <tr align="left">
                <td>Read current date and time from session state:</td>
                <td>         
                    <input type="button" 
                        onclick="GetSessionValue('SessionValue')" 
                        value="Read" />
                </td>
            </tr>
        </table>           
    </center>

    <hr/>

    <span style="background-color:Aqua" id="ResultId"></span>

</body>

</html>

O exemplo a seguir mostra script usado para fazer chamadas a métodos de página.

// PageMethods.js

var displayElement;

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

// Gets the session state value.
function GetSessionValue(key) 
{
    PageMethods.GetSessionValue(key, 
        OnSucceeded, OnFailed);
}

//Sets the session state value.
function SetSessionValue(key, value) 
{
    PageMethods.SetSessionValue(key, value, 
        OnSucceeded, OnFailed);
}

// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "GetSessionValue")
    {
        displayElement.innerHTML = "Current session state value: " + 
            result;
    }
}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if(error !== null) 
    {
        displayElement.innerHTML = "An error occurred: " + 
            error.get_message();
    }
}

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

Para obter mais informações sobre estado de sessão, consulte Visão geral sobre Estado de sessão ASP.NET..

Consulte também

Tarefas

Usando o Controle UpdatePanel com um Serviço da Web

Conceitos

Usando Serviço Web AJAX ASP.NET

Usando Serviço Web AJAX ASP.NET

Expondo Serviços WCF para Scripts de Cliente

Chamando Serviços da Web de Scripts Clientes

Usando Formulários de Autenticação com AJAX do ASP.NET

Usando Perfis de Informações com AJAX do ASP.NET