Созданные прокси-классы
Позволяет приложению осуществлять асинхронный вызов веб-служб с помощью ECMAScript (JavaScript).
Пространство имен: Sys.Net
Наследования: отсутствуют
Конструкторы
Имя |
Описание |
---|---|
Создает новый экземпляр созданного прокси-класса. |
Члены
Имя |
Описание |
---|---|
Вызывает соответствующие методы веб-служб. |
|
Возвращает или задает для созданного прокси-класса и его экземпляров используемую по умолчанию функцию обратного вызова, закончившуюся неудачно. |
|
Получает или задает для созданного прокси-класса и его экземпляров функцию обратного вызова, используемую по умолчанию в случае успешного выполнения исходного вызова. |
|
Возвращает или задает для созданного прокси-класса и его экземпляров используемый по умолчанию контекст пользователя. |
|
Получает и задает URL-адрес веб-службы. |
|
Возвращает или задает интервал времени ожидания для созданного прокси-класса и его экземпляров. |
|
Обрабатывает сведения об ошибке после неудачного запроса метода веб-службы. |
|
Обрабатывает возвращенные данные после успешного выполнения запроса метода веб-службы. |
Примечания
Чтобы вызвать метод веб-службы, следует вызвать соответствующий метод созданного прокси-класса веб-службы. Созданный прокси-класс выполняет веб-запрос в методе веб-службы.
Примечание
Приложения ASP.NET с поддержкой AJAX, вызывающие веб-службы из скрипта, должны быть настроены на регистрацию необходимого обработчика HTTP ASP.NET.Дополнительные сведения см. в разделе Exposing Web Services to Client Script.
Вызываемая веб-служба должна быть файлом .asmx и дополнена атрибутом ScriptServiceAttribute. Отдельные методы, вызываемые из скрипта, быть дополнены атрибутом WebMethodAttribute. Методы без данного атрибута не представлены в прокси-классе. Дополнительные сведения см. в разделах Exposing Web Services to Client Script и Calling Web Services from Client Script.
Прокси-класс создается автоматически при отображении веб-страницы ASP.NET и является производным от класса Sys.Net.WebServiceProxy. Свойство path созданного класса ссылается на URL-адрес веб-службы.
В приложении можно вызвать члены созданного прокси-класса. Или можно создать экземпляры созданного прокси-класса. Можно задать функцию успешно выполненного обратного вызова, функцию обратного вызова, закончившуюся неудачно и, при необходимости, значение времени ожидания и контекст пользователя в качестве свойств по умолчанию для каждого экземпляра. Затем эти экземпляры прокси-класса можно использовать для вызова методов веб-службы.
Пример
Следующий пример кода показывает, как использовать созданный прокси-класс веб-службы. В примере представлены веб-страница, клиентский скрипт и веб-служба, вызванные страницей с помощью клиентского скрипта.
<%@ 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">
<title>Using Generated Web Service Proxy Class</title>
<style type="text/css">
body { font: 11pt Trebuchet MS;
font-color: #000000;
padding-top: 72px;
text-align: center }
.text { font: 10pt Trebuchet MS; text-align: center }
</style>
</head>
<body>
<h2>Using Generated Web Service Proxy Class</h2>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptManager">
<Services>
<asp:ServiceReference Path="UsingProxyClass.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="UsingProxyClass.js" />
</Scripts>
</asp:ScriptManager>
</form>
<center>
<table style="font-size:12px;" >
<tr align="left">
<td class="text">Get Server Object:</td>
<td>
<button id="Button3"
onclick="GetDefaultColor()">Get Default Color</button>
</td>
</tr>
<tr align="left">
<td class="text">Pass Server Object:</td>
<td>
<button id="Button4"
onclick="SetColor()">Set Color</button>
</td>
</tr>
</table>
</center>
<hr />
<!-- Display current color object. -->
<span id="ResultId"></span>
</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" runat="server">
<title>Using Generated Web Service Proxy Class</title>
<style type="text/css">
body { font: 11pt Trebuchet MS;
font-color: #000000;
padding-top: 72px;
text-align: center }
.text { font: 10pt Trebuchet MS; text-align: center }
</style>
</head>
<body>
<h2>Using Generated Web Service Proxy Class</h2>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptManager">
<Services>
<asp:ServiceReference Path="UsingProxyClass.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="UsingProxyClass.js" />
</Scripts>
</asp:ScriptManager>
</form>
<center>
<table style="font-size:12px;" >
<tr align="left">
<td class="text">Get Server Object:</td>
<td>
<button id="Button3"
onclick="GetDefaultColor()">Get Default Color</button>
</td>
</tr>
<tr align="left">
<td class="text">Pass Server Object:</td>
<td>
<button id="Button4"
onclick="SetColor()">Set Color</button>
</td>
</tr>
</table>
</center>
<hr />
<!-- Display current color object. -->
<span id="ResultId"></span>
</body>
</html>
// The Web service default color.
var defaultRgb;
// The proxy class instance.
var proxyInstance;
// The page feedback display element.
var displayResult;
// This function intializes the global variables and
// assigns default values to the generated proxy.
function pageLoad()
{
// Get page feedback display element.
displayResult =
document.getElementById("ResultId");
// Assign default values to the generated proxy.
Samples.AspNet.UsingProxyClass.set_timeout(200);
Samples.AspNet.UsingProxyClass.set_defaultUserContext("Default context");
Samples.AspNet.UsingProxyClass.set_defaultSucceededCallback(SucceededCallback);
Samples.AspNet.UsingProxyClass.set_defaultFailedCallback(FailedCallback);
}
// This function shows how to get
// a server object.
function GetDefaultColor()
{
// Gets the default color obiect.
Samples.AspNet.UsingProxyClass.GetDefaultColor();
}
// This function shows how to instantiate
// the proxy class to assign its default values.
function SetColor()
{
// Instantiate a color object.
var color =
new Samples.AspNet.ColorObject();
// Define a color array (blue).
var colorArray = new Array("00", "00", "FF");
// Assign the new values to the server color object.
color.message = "The new color is Blue";
color.rgb = colorArray;
// Assign default values for the generated proxy using
// a proxy instance.
proxyInstance = new Samples.AspNet.UsingProxyClass();
proxyInstance.set_timeout(1000);
proxyInstance.set_defaultUserContext("New context");
proxyInstance.set_defaultSucceededCallback(SucceededCallback);
proxyInstance.set_defaultFailedCallback(FailedCallback);
// Set the default color object.
proxyInstance.SetColor(color);
}
// Callback function invoked when the call to
// the Web service methods succeeds.
function SucceededCallback(result, userContext, methodName)
{
var message;
switch(methodName)
{
case ("GetDefaultColor"):
case ("SetColor"):
{
// Get the server default color.
message = result.message;
defaultRgb = result.rgb;
// Transform the rgb array into a string.
var serverColor = defaultRgb[0]+ defaultRgb[1] + defaultRgb[2];
// Display the result.
displayResult.style.color = "yellow";
displayResult.style.fontWeight = "bold";
displayResult.style.backgroundColor = "#" + serverColor;
DisplayMessage(message);
break;
}
default:
{
DisplayMessage("Method unknown");
}
}
}
// Callback function invoked when the call to
// the Web service methods fails.
function FailedCallback(error, userContext, methodName)
{
if(error !== null)
{
displayResult.innerHTML = "An error occurred: " +
error.get_message();
}
}
function DisplayMessage(message)
{
if (document.all)
displayResult.innerText = message;
else
// Firefox
displayResult.textContent = message;
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
<%@ WebService Language="C#" Class="Samples.AspNet.UsingProxyClass" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace Samples.AspNet
{
// Define the color type to
// exchange with the client.
public class ColorObject
{
public string message;
public string[] rgb;
public ColorObject()
{
this.message = "The default color is Red";
this.rgb = new string[] { "FF", "00", "00" };
}
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UsingProxyClass :
System.Web.Services.WebService
{
// Note, because the ColorObject is the returned type
// it does not require that you apply
// the attribute [GenerateScriptType(typeof(ColorObject))]
// to the service class to allow client script
// access.
[WebMethod]
public ColorObject GetDefaultColor()
{
// Instantiate the default color object.
ColorObject co = new ColorObject();
return co;
}
[WebMethod]
public ColorObject SetColor(ColorObject color)
{
// Instantiate the color object.
ColorObject co = new ColorObject();
// Assign the passed values.
co.message = color.message;
co.rgb = color.rgb;
return co;
}
}
}
См. также
Основные понятия
Exposing Web Services to Client Script