ServiceReference Класс

Определение

Регистрирует веб-службу для использования на странице.

public ref class ServiceReference
public class ServiceReference
type ServiceReference = class
Public Class ServiceReference
Наследование
ServiceReference

Примеры

В следующем примере показано, как добавить ссылку на веб-службу в разметку страницы для вызова методов веб-службы из скрипта.

<%@ 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" runat="server"> 
        <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>Calling Web Methods</title>    
    </head>
    
    <body>
        <form id="Form1" runat="server">
        
            <asp:ScriptManager runat="server" ID="scriptManagerId">
                <Scripts>
                    <asp:ScriptReference Path="Scripts.js" />
                </Scripts>
                <Services>
                    <asp:ServiceReference  Path="WebService.asmx" />
                </Services>                
            </asp:ScriptManager>
            
            <div>
                <h2>Calling Web Methods</h2>
                 
               <table>
                    <tr align="left">
                        <td>Method that does not return a value:</td>
                        <td>
                            <!-- Getting no retun value from 
                            the Web service. --> 
                            <button id="Button1"  
                                onclick="GetNoReturn()">No Return</button>
                        </td>
                    </tr>
                    
                    <tr align="left">
                        <td>Method that returns a value:</td>
                        <td>
                            <!-- Getting a retun value from 
                            the Web service. --> 
                            <button id="Button2" 
                                onclick="GetTime(); return false;">Server Time</button>
                        </td>
                   </tr>
                   
                   <tr align="left">
                        <td>Method that takes parameters:</td>
                        <td>
                            <!-- Passing simple parameter types to 
                            the Web service. --> 
                            <button id="Button3" 
                                onclick="Add(20, 30); return false;">Add</button>
                        </td>
                       
                    </tr>
                   
                    <tr align="left">
                        <td>Method that returns XML data:</td>
                        <td>   
                             <!-- Get Xml. --> 
                            <button id="Button4" 
                                onclick="GetXmlDocument(); return false;">Get Xml</button>
                        </td>
                    </tr>
                    <tr align="left">
                        <td>Method that uses GET:</td>
                        <td>   
                             <!-- Making a GET Web request. --> 
                            <button id="Button5" 
                                onclick="MakeGetRequest(); return false;">Make GET Request</button>
                        </td>
                    </tr>
                    
                </table>
         
            </div>
        </form>
        
        <hr/>
        
        <div>
            <span id="ResultId"></span>
        </div>   
        
    </body>
    
</html>
<%@ 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" runat="server"> 
        <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>Calling Web Methods</title>    
    </head>
    
    <body>
        <form id="Form1" runat="server">
        
            <asp:ScriptManager runat="server" ID="scriptManagerId">
                <Scripts>
                    <asp:ScriptReference Path="Scripts.js" />
                </Scripts>
                <Services>
                    <asp:ServiceReference  Path="WebService.asmx" />
                </Services>                
            </asp:ScriptManager>
            
            <div>
                <h2>Calling Web Methods</h2>
                 
               <table>
                    <tr align="left">
                        <td>Method that does not return a value:</td>
                        <td>
                            <!-- Getting no retun value from 
                            the Web service. --> 
                            <button id="Button1"  
                                onclick="GetNoReturn()">No Return</button>
                        </td>
                    </tr>
                    
                    <tr align="left">
                        <td>Method that returns a value:</td>
                        <td>
                            <!-- Getting a retun value from 
                            the Web service. --> 
                            <button id="Button2" 
                                onclick="GetTime(); return false;">Server Time</button>
                        </td>
                   </tr>
                   
                   <tr align="left">
                        <td>Method that takes parameters:</td>
                        <td>
                            <!-- Passing simple parameter types to 
                            the Web service. --> 
                            <button id="Button3" 
                                onclick="Add(20, 30); return false;">Add</button>
                        </td>
                       
                    </tr>
                   
                    <tr align="left">
                        <td>Method that returns XML data:</td>
                        <td>   
                             <!-- Get Xml. --> 
                            <button id="Button4" 
                                onclick="GetXmlDocument(); return false;">Get Xml</button>
                        </td>
                    </tr>
                    <tr align="left">
                        <td>Method that uses GET:</td>
                        <td>   
                             <!-- Making a GET Web request. --> 
                            <button id="Button5" 
                                onclick="MakeGetRequest(); return false;">Make GET Request</button>
                        </td>
                    </tr>
                    
                </table>
         
            </div>
        </form>
        
        <hr/>
        
        <div>
            <span id="ResultId"></span>
        </div>   
        
    </body>
    
</html>

Комментарии

Чтобы вызвать методы веб-службы из ECMAScript (JavaScript), необходимо включить ссылку на службу на странице ASP.NET и применить ScriptServiceAttribute атрибут к определению класса веб-службы. Если вы включите ссылку на веб-службу в ScriptManager элемент управления или ScriptManagerProxy на странице ASP.NET, объекты JavaScript будут создаваться в браузере.

Прокси-объекты будут использоваться для выполнения следующих действий:

  • Выполнение асинхронных запросов в javaScript к методам веб-службы;

  • Инициализируйте экземпляры прокси-серверов типов данных, в частности для использования в качестве входных параметров для вызова веб-методов.

Примечание

Элемент ServiceReference управления можно использовать только для служб в том же домене.

Расположение веб-службы можно определить декларативно, добавив <asp:ServiceReference> элемент <Services> в элемент внутри <asp:ScriptManager> элемента на странице, а затем задав его Path атрибут, как показано в следующем примере.

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

Можно использовать свойство , InlineScript чтобы указать, включен ли скрипт создания прокси-сервера на страницу в виде встроенного блока скрипта или получен с помощью отдельного запроса.

Можно также программным способом ServiceReference добавить объект через коллекцию ScriptManager.Services или ScriptManagerProxy.Services с помощью Add метода ServiceReferenceCollection класса .

Конструкторы

ServiceReference()

Инициализирует новый экземпляр класса ServiceReference.

ServiceReference(String)

Инициализирует новый экземпляр класса ServiceReference с указанным путем.

Свойства

InlineScript

Возвращает или задает значение, которое указывает, включается ли скрипт формирования прокси в страницу в качестве встроенного блока скрипта, или получается по отдельному запросу.

Path

Возвращает или задает путь для веб-службы, на которую указывает ссылка.

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetProxyScript(ScriptManager, Control)

Предоставляет скрипт прокси из производного объекта ServiceReference, который можно переопределить как настраиваемый.

GetProxyUrl(ScriptManager, Control)

Предоставляет URL прокси из производного объекта ServiceReference, который можно переопределить как настраиваемый.

GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, которая представляет значение свойства Path или имя типа.

Применяется к

См. также раздел