Бөлісу құралы:


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 атрибут к определению класса веб-службы. Если вы включаете ссылку на службу в веб-службу или ScriptManagerScriptManagerProxy элемент управления на странице 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 свойства или имени типа.

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

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