- Windows Web Services Examples
- Service Model Examples
- TCP Channel Layer Examples
- HTTP Channel Layer Examples
- UDP Channel Layer Examples
- Named Pipes Channel Layer Examples
- Message Examples
- XML Examples
- Async Model Examples
- Security Channel Layer Examples
- Metadata Example
- WS-Metadata Exchange Example
- Custom headers and Service model
- File Replication Sample
- WCF Public Service Interoperation
- Custom HTTP Proxy
- Write a web service by using Visual C# .NET
- Requirements
- Write an .asmx web service
- Consume a web service
- References
- Практическое руководство. Связывание с веб-службой с помощью компонента BindingSource в Windows Forms How to: Bind to a Web Service Using the Windows Forms BindingSource
- Создание и привязка к прокси на стороне клиента To create and bind to a client-side proxy
- Привязка элементов управления к компоненту BindingSource, который привязан к веб-службе To bind controls to the BindingSource that is bound to a Web service
- Пример Example
- Компиляция кода Compiling the Code
- Введение в веб-службы Introduction to Web Services
- REST REST
- Использование служб RESTFUL Consuming REST Services
- HttpClient HttpClient
- HTTPWebRequest HTTPWebRequest
- RestSharp RestSharp
- нсурлконнектион NSUrlConnection
- ServiceStack ServiceStack
- Использование данных RESTFUL Consuming RESTful Data
- System.JSНА System.JSON
- JSON.NET JSON.NET
- ServiceStack. Text ServiceStack.Text
- System.Xml.Linq System.Xml.Linq
- Веб-служба ASP.NET (ASMX) ASP.NET Web Service (ASMX)
- Создание учетной записи-посредника Generating a Proxy
- Добавление прокси-сервера в проект вручную Manually Adding a Proxy to a Project
- Использование прокси-сервера Consuming the Proxy
- Windows Communication Foundation (WCF) Windows Communication Foundation (WCF)
- Создание учетной записи-посредника Generating a Proxy
- Настройка прокси-сервера Configuring the Proxy
- Использование прокси-сервера Consuming the Proxy
- Использование безопасности транспорта Using Transport Security
- Использование безопасности учетных данных клиента Using Client Credential Security
Windows Web Services Examples
The following examples show how to use Windows Web Services API.
Service Model Examples
Service that handles raw (non-SOAP) HTTP requests: Client:HttpRawClientExample. Server:HttpRawServiceExample.
Manually create a policy description and use it to create a service proxy: PolicyTemplateExample.
TCP Channel Layer Examples
A TCP example that sends messages using a one-way pattern: Client: OneWayTcpClientExample, Server: OneWayTcpServerExample
A TCP example that sends messages using a request-reply pattern: Client: RequestReplyTcpClientExample, Server: RequestReplyTcpServerExample
HTTP Channel Layer Examples
An HTTP example that uses the streaming APIs: Client: StreamingHttpClientExample, Server: StreamingHttpServerExample
UDP Channel Layer Examples
A UDP example that sends messages using a one-way pattern: Client: OneWayUdpClientExample, Server: OneWayUdpServerExample
A UDP example that sends messages using a multicast request response pattern: Client: MulticastUdpClientExample, Server: MulticastUdpServerExample The following is the same example, but using IPv6 addressing: Client: MulticastUdpClientExample6, Server: MulticastUdpServerExample6
Named Pipes Channel Layer Examples
A named pipes example that sends messages using a request-reply pattern: Client: RequestReplyNamedPipesClientExample, Server: RequestReplyNamedPipesServerExample
Message Examples
An example that uses custom message headers: CustomHeaderExample
An example that encodes and decodes a message: MessageEncodingExample
An example that forwards a message: ForwardMessageExample
XML Examples
An example that writes and reads xml using an XML buffer ReadWriteXmlExample
An example that writes and reads binary data using MTOM, WsWriteBytes, WsPushBytes, and WsPullBytes ReadWriteBytesXmlExample
An example that navigates an XML buffer NavigateXmlExample
An example that reads an XML document node by node ReadXmlExample
An example that find and displays an XML attribute ReadAttributeExample
An example that writes and reads an array of elements ReadWriteArrayExample
An example that inserts an element into an XML buffer InsertElementExample
An example that shows the use of some XML buffer helper functions XmlBufferExample
An example that writes and reads derived type using wsutil generated helper functions DerivedTypeExample
Async Model Examples
An example that illustrates the model for asynchronous functions. AsyncModelExample
Security Channel Layer Examples
Metadata Example
The following examples show how to process WSDL and Policy documents with the goal of extracting information about what protocol an endpoint supports.
Username over SSL mixed-mode security: MetadataImportWithUsernameOverSslExample. Issued token over SSL mixed-mode security: MetadataImportWithIssuedTokenOverSslExample. X509 certificate over SSL mixed-mode security: MetadataImportWithX509OverSslExample.
WS-Metadata Exchange Example
The following examples show how to enable WS-MetadataExchange on WS_SERVICE_HOST.
TCP service with WS-MetadataExchange enabled: MetadataExchangeSample. WCF service moniker client which calls into the TCP service with WS-MetadataExchange enabled: ServiceMonikerSample.
Custom headers and Service model
The following examples show how to use custom headers with WS_SERVICE_PROXY and WS_SERVICE_HOST respectively.
File Replication Sample
A comprehensive sample that demonstrates how to implement a file replication service: Tool: FileRepToolExample, Service: FileRepServiceExample.
WCF Public Service Interoperation
A Windows Web Services client communicates with a WCF service Client: WcfPublicServiceSample.
Custom HTTP Proxy
A Windows Web Services client communicates with a ASMX TerraService service using custom proxy Client: AsmxTerraServiceSampleWithCustomProxy
Write a web service by using Visual C# .NET
This article helps you write a web service, called MathService, that exposes methods for adding, subtracting, dividing, and multiplying two numbers.
Original product version: В Visual C# .NET
Original KB number: В 308359
Requirements
The following list describes the recommended hardware, software, skills and knowledge that you need:
- Microsoft Windows
- Internet Information Server
- Visual Studio .NET
This article assumes that you’re familiar with the topic: How to use the Visual Studio .NET integrated development environment.
Write an .asmx web service
Open Visual Studio .NET.
On the File menu, select New and select Project. Under Project types, select Visual C# Projects. Then select ASP.NET Web Service under Templates. Type MathService in the Location text box to change the default name (WebService1) to MathService.
Change the name of the default Web service that is created from Service1.asmx to MathService.asmx.
Select Click to switch to code view in the designer environment.
Define methods that encapsulate the functionality of your service. Each method that will be exposed from the service must be flagged with a WebMethod attribute in front of it. Without this attribute, the method will not be exposed from the service.
Not every method needs to have the WebMethod attribute. It’s useful to hide some implementation details called by public web service methods or for the case in which the WebService class is also used in local applications. A local application can use any public class, but only WebMethod methods will be remotely accessible as web services.
Add the following method to the MathServices class that you created:
Select Build on the Build menu to build the web service.
Browse to the MathService.asmx Web service page to test the web service. If you set the local computer to host the page, the URL is http://localhost/MathService/MathService.asmx .
The ASP.NET runtime returns a web Service Help Page that describes the Web service. This page also enables you to test different web service methods.
Consume a web service
Open Visual Studio .NET.
Under Project types, select Visual C# Projects, then select Console Application under Templates.
Add a reference for the MathService web service to the new console application.
This step creates a proxy class on the client computer. After the proxy class exists, you can create objects based on the class. Each method call that is made with the object then goes out to the uniform resource identifier (URI) of the web service (usually as a SOAP request).
- On the Project menu, select Add Web Reference.
- In the Add Web Reference dialog box, type the URL for the web service in the Address text box and press ENTER. If you set the local computer to host the web service, the URL is http://localhost/MathService/MathService.asmx .
- Select Add Reference. Alternatively, you can type the URL to the discovery file (MathService.vsdisco) or select Web References on Local Web Server in the left pane to select the MathService service from the list.
- Expand the Web References section of Solution Explorer and note the namespace that was used.
Create an instance of the proxy object that was created. Place the following code in the function called Main :
Invoke a method on the proxy object that you created in the previous step, as follows:
Select Build on the Build menu to build the console application.
Select Start on the Debug menu to test the application.
Close and save the project.
References
For more information, see the Programming the Web with Web Services topic in the Visual Studio .NET Help, or the ASP.NET Web Services and ASP.NET Web Service Clients topic in the .NET Framework Developer’s Guide.
For more information, see the following websites:
Практическое руководство. Связывание с веб-службой с помощью компонента BindingSource в Windows Forms How to: Bind to a Web Service Using the Windows Forms BindingSource
Компонент BindingSource можно использовать, если необходимо привязать элемент управления Windows Form к результатам вызова веб-служб XML. If you want to bind a Windows Form control to the results obtained from calling an XML Web service, you can use a BindingSource component. Эта процедура аналогична привязке компонента BindingSource к типу. This procedure is similar to binding a BindingSource component to a type. Необходимо создать клиентский прокси, который содержит методы и типы, предоставляемые веб-службой. You must create a client-side proxy that contains the methods and types exposed by the Web service. Клиентский прокси веб-службы можно создать либо непосредственно в самой веб-службе (ASMX-файл) или с помощью файла языка описания веб-служб (WSDL-файл). You generate a client-side proxy from the Web service (.asmx) itself, or its Web Services Description Language (WSDL) file. Кроме того, клиентский прокси должен предоставлять доступ к полям сложных типов, используемых веб-службой, в виде общих свойств. Additionally, your client-side proxy must expose the fields of complex types used by the Web service as public properties. Затем BindingSource привязывается к одному из типов, доступных в прокси веб-службы. You then bind the BindingSource to one of the types exposed in the Web service proxy.
Создание и привязка к прокси на стороне клиента To create and bind to a client-side proxy
Создайте форму Windows Forms в каталоге по своему усмотрению с подходящим пространством имен. Create a Windows Form in the directory of your choice, with an appropriate namespace.
Добавьте в форму компонент BindingSource. Add a BindingSource component to the form.
Откройте командную строку пакета средств разработки программного обеспечения Windows (SDK) и перейдите в тот же каталог, в котором находится ваша форма. Open the Windows Software Development Kit (SDK) command prompt, and navigate to the same directory that your form is located in.
С помощью средства WSDL введите wsdl и URL-адрес для ASMX- или WSDL-файла веб-службы, пространство имен приложения и при необходимости язык, с которым вы работаете. Using the WSDL tool, enter wsdl and the URL for the .asmx or WSDL file for the Web service, followed by the namespace of your application, and optionally the language you are working in.
В следующем примере кода используется веб-служба, расположенная по адресу http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx . The following code example uses the Web service located at http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx . Например, для C# типа wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService или для Visual Basic введите wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService /language:VB . For example, for C# type wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService , or for Visual Basic type wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService /language:VB . Передача пути в качестве аргумента для средства WSDL создаст клиентский прокси в том же каталоге и с тем пространством имен, что и у приложения, и на указанном языке. Passing the path as an argument to the WSDL tool will generate a client-side proxy in the same directory and namespace as your application, in the specified language. Если вы используете Visual Studio, добавьте файл в проект. If you are using Visual Studio, add the file to your project.
Выберите тип для привязки в клиентском прокси. Select a type in the client-side proxy to bind to.
Обычно это тип, возвращаемый методом, предлагаемым веб-службой. This is typically a type returned by a method offered by the Web service. Поля выбранного типа должны предоставляться как общие свойства для привязки. The fields of the chosen type must be exposed as public properties for binding purposes.
Задайте для свойства DataSource в BindingSource нужный тип, содержащийся в клиентском прокси веб-службы. Set the DataSource property of the BindingSource to the type you want that is contained in the Web service client-side proxy.
Привязка элементов управления к компоненту BindingSource, который привязан к веб-службе To bind controls to the BindingSource that is bound to a Web service
Привяжите элементы управления к BindingSource, передав в качестве параметра общее свойство типа веб-службы. Bind controls to the BindingSource, passing the public property of the Web service type that you want as a parameter.
Пример Example
В следующем примере кода показано, как привязать компонент BindingSource к веб-службе, а затем привязать текстовое поле к компоненту BindingSource. The following code example demonstrates how to bind a BindingSource component to a Web service, and then how to bind a text box to the BindingSource component. При нажатии кнопки вызывается метод веб-службы, результаты будут отображаться в textbox1 . When you click the button, a Web service method is called and the results will appear in textbox1 .
Компиляция кода Compiling the Code
Это завершенный пример, включающий метод Main и сокращенную версию кода клиентского прокси. This is a complete example that includes a Main method, and a shortened version of client-side proxy code.
Для этого примера требуются: This example requires:
Введение в веб-службы Introduction to Web Services
В этом руководстве показано, как использовать различные технологии веб-служб. Рассматриваемые темы включают взаимодействие со службами RESTFUL, службами SOAP и службами Windows Communication Foundation. This guide demonstrates how to consume different web service technologies. Topics covered include communicating with REST services, SOAP services, and Windows Communication Foundation services.
Для правильной работы многие мобильные приложения зависят от облака, и поэтому интеграция веб-служб в мобильные приложения является распространенным сценарием. To function correctly, many mobile applications are dependent on the cloud, and so integrating web services into mobile applications is a common scenario. Платформа Xamarin поддерживает использование различных технологий веб-служб и включает в себя встроенную и сторонние службы для использования служб RESTFUL, ASMX и Windows Communication Foundation (WCF). The Xamarin platform supports consuming different web service technologies, and includes in-built and third-party support for consuming RESTful, ASMX, and Windows Communication Foundation (WCF) services.
Для клиентов, использующих Xamarin. Forms, существуют полные примеры использования каждой из этих технологий в документации по веб-службам Xamarin. Forms . For customers using Xamarin.Forms, there are complete examples using each of these technologies in the Xamarin.Forms Web Services documentation.
В iOS 9 Защита транспорта приложений (ATS) обеспечивает безопасное подключение между Интернет-ресурсами (например, серверным сервером приложения) и приложением, тем самым предотвращая случайное раскрытие конфиденциальной информации. In iOS 9, App Transport Security (ATS) enforces secure connections between internet resources (such as the app’s back-end server) and the app, thereby preventing accidental disclosure of sensitive information. Поскольку ATS включена по умолчанию в приложениях, созданных для iOS 9, все подключения будут подвергаться требованиям безопасности ATS. Since ATS is enabled by default in apps built for iOS 9, all connections will be subject to ATS security requirements. Если соединения не соответствуют этим требованиям, они завершатся сбоем с исключением. If connections do not meet these requirements, they will fail with an exception.
Можно отказаться от ATS, если невозможно использовать HTTPS протокол и обеспечить безопасную связь для Интернет-ресурсов. You can opt-out of ATS if it is not possible to use the HTTPS protocol and secure communication for internet resources. Это можно сделать, обновив файл info. plist приложения. This can be achieved by updating the app’s Info.plist file. Дополнительные сведения см. в статье Безопасность транспорта приложений. For more information see App Transport Security.
REST REST
Перестроение данных о состоянии (остальное) — это архитектурный стиль для создания веб-служб. Representational State Transfer (REST) is an architectural style for building web services. Запросы RESTFUL выполняются по протоколу HTTP с использованием тех же глаголов HTTP, которые используются веб-браузерами для получения веб-страниц и отправки данных на серверы. REST requests are made over HTTP using the same HTTP verbs that web browsers use to retrieve web pages and to send data to servers. Команды: The verbs are:
- Get — эта операция используется для получения данных из веб-службы. GET – this operation is used to retrieve data from the web service.
- POST — эта операция используется для создания нового элемента данных в веб-службе. POST – this operation is used to create a new item of data on the web service.
- Разместить — эта операция используется для обновления элемента данных в веб-службе. PUT – this operation is used to update an item of data on the web service.
- Patch — эта операция используется для обновления элемента данных веб-службы путем описания набора инструкций по изменению элемента. PATCH – this operation is used to update an item of data on the web service by describing a set of instructions about how the item should be modified. Эта команда не используется в примере приложения. This verb is not used in the sample application.
- Delete — эта операция используется для удаления элемента данных в веб-службе. DELETE – this operation is used to delete an item of data on the web service.
API веб-службы, которые соответствуют ОСТАВШИМся, называются API RESTFUL и определяются с помощью: Web service APIs that adhere to REST are called RESTful APIs, and are defined using:
- Базовый URI. A base URI.
- Методы HTTP, такие как GET, POST, WHERE, PATCH или DELETE. HTTP methods, such as GET, POST, PUT, PATCH, or DELETE.
- Тип мультимедиа для данных, например нотация объектов JavaScript (JSON). A media type for the data, such as JavaScript Object Notation (JSON).
Простота работы с другими позволила сделать ее основным методом доступа к веб-службам в мобильных приложениях. The simplicity of REST has helped make it the primary method for accessing web services in mobile applications.
Использование служб RESTFUL Consuming REST Services
Существует несколько библиотек и классов, которые можно использовать для использования служб RESTFUL, а следующие подразделы обсуждают их. There are a number of libraries and classes that can be used to consume REST services, and the following subsections discuss them. Дополнительные сведения об использовании службы RESTFUL см. в статье Использование веб-службы RESTful. For more information about consuming a REST service, see Consume a RESTful Web Service.
HttpClient HttpClient
Клиентские библиотеки Microsoft HTTP предоставляют HttpClient класс, который используется для отправки и получения запросов по протоколу HTTP. The Microsoft HTTP Client Libraries provides the HttpClient class, which is used to send and receive requests over HTTP. Он предоставляет функциональные возможности для отправки HTTP-запросов и получения HTTP-ответов из ресурса, идентифицированного с помощью URI. It provides functionality for sending HTTP requests and receiving HTTP responses from a URI-identified resource. Каждый запрос отправляется как асинхронная операция. Each request is sent as an asynchronous operation. Дополнительные сведения об асинхронных операциях см. в разделе Общие сведения о поддержке асинхронныхопераций. For more information about asynchronous operations, see Async Support Overview.
HttpResponseMessage Класс представляет сообщение HTTP-ответа, полученное от веб службы после выполнения запроса HTTP. The HttpResponseMessage class represents an HTTP response message received from the web service after an HTTP request has been made. Он содержит сведения о ответе, включая код состояния, заголовки и текст. It contains information about the response, including the status code, headers, and body. HttpContent Класс представляет тело HTTP и заголовки содержимого, таких как Content-Type и Content-Encoding . The HttpContent class represents the HTTP body and content headers, such as Content-Type and Content-Encoding . Содержимое может быть считано с помощью любого из ReadAs методов, например ReadAsStringAsync и ReadAsByteArrayAsync , в зависимости от формата данных. The content can be read using any of the ReadAs methods, such as ReadAsStringAsync and ReadAsByteArrayAsync , depending upon the format of the data.
Дополнительные сведения о HttpClient классе см. в разделе Создание объекта HttpClient. For more information about the HttpClient class, see Creating the HTTPClient Object.
HTTPWebRequest HTTPWebRequest
Для вызова веб-служб HTTPWebRequest используется: Calling web services with HTTPWebRequest involves:
- Создание экземпляра запроса для конкретного URI. Creating the request instance for a particular URI.
- Задание различных свойств HTTP для экземпляра запроса. Setting various HTTP properties on the request instance.
- Получение HttpWebResponse из запроса. Retrieving an HttpWebResponse from the request.
- Считывание данных из ответа. Reading data out of the response.
Например, следующий код извлекает данные из национальной библиотеки США веб-службы медицина: For example, the following code retrieves data from the U.S. National Library of Medicine web service:
В приведенном выше примере создается объект HttpWebRequest , который будет возвращать данные в формате JSON. The above example creates an HttpWebRequest that will return data formatted as JSON. Данные возвращаются в HttpWebResponse , из которого StreamReader можно получить для чтения данных. The data is returned in an HttpWebResponse , from which a StreamReader can be obtained to read the data.
RestSharp RestSharp
Другой подход к использованию служб RESTFUL — использование библиотеки рестшарп . Another approach to consuming REST services is using the RestSharp library. Рестшарп инкапсулирует HTTP-запросы, включая поддержку получения результатов в виде содержимого необработанной строки или в виде десериализованного объекта C#. RestSharp encapsulates HTTP requests, including support for retrieving results either as raw string content or as a deserialized C# object. Например, следующий код выполняет запрос к международной библиотеке медицина веб-службы США и получает результаты в виде строки в формате JSON: For example, the following code makes a request to the U.S. National Library of Medicine web service, and retrieves the results as a JSON formatted string:
DeserializeRxTerm — Это метод, который принимает необработанную строку JSON из RestSharp.RestResponse.Content Свойства и преобразует ее в объект C#. DeserializeRxTerm is a method that will take the raw JSON string from the RestSharp.RestResponse.Content property and convert it into a C# object. Десериализация данных, возвращаемых веб-службами, обсуждается далее в этой статье. Deserializing data returned from web services is discussed later in this article.
нсурлконнектион NSUrlConnection
Помимо классов, доступных в библиотеке базовых классов Mono (BCL), например HttpWebRequest , и сторонних библиотек C#, таких как рестшарп, классы для конкретных платформ также доступны для использования веб-служб. In addition to classes available in the Mono base class library (BCL), such as HttpWebRequest , and third party C# libraries, such as RestSharp, platform-specific classes are also available for consuming web services. Например, в iOS NSUrlConnection NSMutableUrlRequest можно использовать классы и. For example, in iOS, the NSUrlConnection and NSMutableUrlRequest classes can be used.
В следующем примере кода показано, как вызвать стандартную библиотеку США для веб-службы медицина с помощью классов iOS: The following code example shows how to call the U.S. National Library of Medicine web service using iOS classes:
Как правило, классы платформы для использования веб-служб должны быть ограничены сценариями, в которых машинный код переносится в C#. Generally, platform-specific classes for consuming web services should be limited to scenarios where native code is being ported to C#. Там, где это возможно, код доступа к веб-службе должен быть переносимым, чтобы его можно было совместно использовать на разных платформах. Where possible, web service access code should be portable so that it can be shared cross-platform.
ServiceStack ServiceStack
Другим вариантом вызова веб-служб является библиотека стека обслуживания . Another option for calling web services is the Service Stack library. Например, в следующем коде показано, как использовать метод стека службы IServiceClient.GetAsync для выдаче запроса на обслуживание: For example, the following code shows how to use Service Stack’s IServiceClient.GetAsync method to issue a service request:
Хотя такие средства, как ServiceStack и Рестшарп, упрощают вызов и использование служб RESTFUL, иногда нетривиальным является использование XML или JSON, который не соответствует стандартным соглашениям о сериализации DataContract . While tools like ServiceStack and RestSharp make it easy to call and consume REST services, it is sometimes non-trivial to consume XML or JSON that does not conform to the standard DataContract serialization conventions. При необходимости вызовите запрос и выполните соответствующую сериализацию явным образом с помощью библиотеки ServiceStack. Text, описанной ниже. If necessary, invoke the request and handle the appropriate serialization explicitly using the ServiceStack.Text library discussed below.
Использование данных RESTFUL Consuming RESTful Data
Веб-службы RESTFUL обычно используют сообщения JSON для возврата данных клиенту. RESTful web services typically use JSON messages to return data to the client. JSON — это текстовый формат обмена данными, создающий компактные полезные данные, что приводит к снижению требований к пропускной способности при отправке данных. JSON is a text-based, data-interchange format that produces compact payloads, which results in reduced bandwidth requirements when sending data. В этом разделе будут проверяться механизмы использования ответов RESTFUL в JSON и обычных-Old-XML (POX). In this section, mechanisms for consuming RESTful responses in JSON and Plain-Old-XML (POX) will be examined.
System.JSНА System.JSON
Платформа Xamarin поставляется без поддержки JSON. The Xamarin platform ships with support for JSON out of the box. С помощью JsonObject можно получить результаты, как показано в следующем примере кода: By using a JsonObject , results can be retrieved as shown in the following code example:
Однако важно помнить, что System.Json средства полностью загружают данные в память. However, it’s important to be aware that the System.Json tools load the entirety of the data into memory.
JSON.NET JSON.NET
Библиотека NewtonSoft JSON.NET — широко используемая библиотека для сериализации и десериализации сообщений JSON. The NewtonSoft JSON.NET library is a widely used library for serializing and deserializing JSON messages. В следующем примере кода показано, как использовать JSON.NET для десериализации сообщения JSON в объект C#: The following code example shows how to use JSON.NET to deserialize a JSON message into a C# object:
ServiceStack. Text ServiceStack.Text
ServiceStack. Text — это библиотека сериализации JSON, предназначенная для работы с библиотекой ServiceStack. ServiceStack.Text is a JSON serialization library designed to work with the ServiceStack library. В следующем примере кода показано, как выполнить синтаксический анализ JSON с помощью ServiceStack.Text.JsonObject : The following code example shows how to parse JSON using a ServiceStack.Text.JsonObject :
System.Xml.Linq System.Xml.Linq
В случае использования веб-службы RESTFUL на основе XML LINQ to XML можно использовать для анализа XML и заполнения встроенного объекта C#, как показано в следующем примере кода: In the event of consuming an XML-based REST web service, LINQ to XML can be used to parse the XML and populate a C# object inline, as demonstrated in the following code example:
Веб-служба ASP.NET (ASMX) ASP.NET Web Service (ASMX)
ASMX предоставляет возможность создавать веб-службы, которые отправляют сообщения с помощью протокола SOAP. ASMX provides the ability to build web services that send messages using the Simple Object Access Protocol (SOAP). SOAP — это независимый от платформы и не зависящий от языка протокол для создания веб-служб и доступа к ним. SOAP is a platform-independent and language-independent protocol for building and accessing web services. Потребители службы ASMX не должны знать ничего о платформе, объектной модели или языке программирования, используемом для реализации службы. Consumers of an ASMX service do not need to know anything about the platform, object model, or programming language used to implement the service. Им нужно только разобраться, как отправлять и получать сообщения SOAP. They only need to understand how to send and receive SOAP messages.
Сообщение SOAP — это XML-документ, содержащий следующие элементы: A SOAP message is an XML document containing the following elements:
- Корневой элемент с именем конверт , ОПРЕДЕЛЯЮЩИЙ XML-документ как сообщение SOAP. A root element named Envelope that identifies the XML document as a SOAP message.
- Необязательный элемент заголовка , содержащий сведения, относящиеся к приложению, такие как данные проверки подлинности. An optional Header element that contains application-specific information such as authentication data. Если элемент Header представлен, он должен быть первым дочерним элементом элемента конверта . If the Header element is present it must be the first child element of the Envelope element.
- Обязательный элемент Body , СОДЕРЖАЩИЙ сообщение SOAP, предназначенное для получателя. A required Body element that contains the SOAP message intended for the recipient.
- Необязательный элемент fault , который используется для указания сообщений об ошибках. An optional Fault element that’s used to indicate error messages. Если элемент fault имеется, он должен быть дочерним элементом элемента Body . If the Fault element is present, it must be a child element of the Body element.
SOAP может использовать несколько транспортных протоколов, включая HTTP, SMTP, TCP и UDP. SOAP can operate over many transport protocols, including HTTP, SMTP, TCP, and UDP. Однако служба ASMX может взаимодействовать только по протоколу HTTP. However, an ASMX service can only operate over HTTP. Платформа Xamarin поддерживает стандартные реализации SOAP 1,1 по протоколу HTTP и включает поддержку многих стандартных конфигураций службы ASMX. The Xamarin platform supports standard SOAP 1.1 implementations over HTTP, and this includes support for many of the standard ASMX service configurations.
Создание учетной записи-посредника Generating a Proxy
Для использования службы ASMX необходимо создать прокси-сервер , который позволяет приложению подключаться к службе. A proxy must be generated to consume an ASMX service, which allows the application to connect to the service. Прокси-сервер создается путем использования метаданных службы, определяющих методы и конфигурацию связанной службы. The proxy is constructed by consuming service metadata that defines the methods and associated service configuration. Эти метаданные предоставляются в виде документа языка описания веб-служб (WSDL), созданного веб-службой. This metadata is exposed as a Web Services Description Language (WSDL) document that is generated by the web service. Прокси-сервер строится с помощью Visual Studio для Mac или Visual Studio, чтобы добавить веб-ссылку на веб – службу для проектов конкретной платформы. The proxy is built by using Visual Studio for Mac or Visual Studio to add a web reference for the web service to the platform-specific projects.
URL веб-службы может быть размещенным удаленным источником или локальным ресурсом файловой системы, доступным по file:/// префиксу пути, например: The web service URL can either be a hosted remote source or local file system resource accessible via the file:/// path prefix, for example:
При этом создается прокси-сервер в папке Web или Service References проекта. This generates the proxy in the Web or Service References folder of the project. Так как прокси-сервер создан, он не должен изменяться. Since a proxy is generated code, it should not be modified.
Добавление прокси-сервера в проект вручную Manually Adding a Proxy to a Project
При наличии существующего прокси-сервера, созданного с помощью совместимых средств, эти выходные данные можно использовать при включении в состав проекта. If you have an existing proxy that has been generated using compatible tools, this output can be consumed when included as part of your project. В Visual Studio для Mac используйте Добавление файлов. In Visual Studio for Mac, use the Add files… пункт меню, чтобы добавить прокси-сервер. menu option to add the proxy. Кроме того, для этого требуется явная ссылка на System.Web.Services.dll с помощью команды Добавить ссылки. In addition, this requires System.Web.Services.dll to be referenced explicitly using the Add References… . dialog.
Использование прокси-сервера Consuming the Proxy
Созданные классы прокси предоставляют методы для использования веб-службы, использующей шаблон разработки модели асинхронного программирования (APM). The generated proxy classes provide methods for consuming the web service that use the Asynchronous Programming Model (APM) design pattern. В этом шаблоне асинхронная операция реализуется в виде двух методов с именами бегиноператионнаме и ендоператионнаме, которые начинают и завершают асинхронную операцию. In this pattern an asynchronous operation is implemented as two methods named BeginOperationName and EndOperationName, which begin and end the asynchronous operation.
Метод бегиноператионнаме начинает асинхронную операцию и возвращает объект, реализующий IAsyncResult интерфейс. The BeginOperationName method begins the asynchronous operation and returns an object that implements the IAsyncResult interface. После вызова бегиноператионнамеприложение может продолжить выполнение инструкций в вызывающем потоке, в то время как асинхронная операция выполняется в потоке пула потоков. After calling BeginOperationName, an application can continue executing instructions on the calling thread, while the asynchronous operation takes place on a thread pool thread.
Для каждого вызова бегиноператионнамеприложение должно также вызывать ендоператионнаме для получения результатов операции. For each call to BeginOperationName, the application should also call EndOperationName to get the results of the operation. Возвращаемое значение ендоператионнаме имеет тот же тип, что и синхронный метод веб-службы. The return value of EndOperationName is the same type returned by the synchronous web service method. В следующем коде показан пример такого действия: The following code example shows an example of this:
Библиотека параллельных задач (TPL) может упростить процесс использования пары методов Begin и End APM, инкапсулирующие асинхронные операции в одном Task объекте. The Task Parallel Library (TPL) can simplify the process of consuming an APM begin/end method pair by encapsulating the asynchronous operations in the same Task object. Это инкапсуляция обеспечивается несколькими перегрузками Task.Factory.FromAsync метода. This encapsulation is provided by multiple overloads of the Task.Factory.FromAsync method. Этот метод создает Task , который выполняет TodoService.EndGetTodoItems метод после TodoService.BeginGetTodoItems завершения метода с null параметром, указывающим, что данные не передаются в BeginGetTodoItems делегат. This method creates a Task that executes the TodoService.EndGetTodoItems method once the TodoService.BeginGetTodoItems method completes, with the null parameter indicating that no data is being passed into the BeginGetTodoItems delegate. Наконец, значение TaskCreationOptions перечисления указывает, что следует использовать поведение по умолчанию для создания и выполнения задач. Finally, the value of the TaskCreationOptions enumeration specifies that the default behavior for the creation and execution of tasks should be used.
Дополнительные сведения об использовании службы ASMX см. в статье Использование веб-службы ASP.NET (ASMX). For more information about consuming an ASMX service, see Consume an ASP.NET Web Service (ASMX).
Windows Communication Foundation (WCF) Windows Communication Foundation (WCF)
WCF — это единая платформа Майкрософт для создания приложений, ориентированных на службы. WCF is Microsoft’s unified framework for building service-oriented applications. Она позволяет разработчикам создавать безопасные, надежные, транзакционные и совместимые распределенные приложения. It enables developers to build secure, reliable, transacted, and interoperable distributed applications.
WCF описывает службу с множеством различных контрактов, которые включают следующее: WCF describes a service with a variety of different contracts which include the following:
- Контракты данных — определяют структуры данных, которые формируют базу содержимого в сообщении. Data contracts – define the data structures that form the basis for the content within a message.
- Контракты сообщений — Составление сообщений из существующих контрактов данных. Message contracts – compose messages from existing data contracts.
- Контракты ошибок — разрешить указывать пользовательские ошибки SOAP. Fault contracts – allow custom SOAP faults to be specified.
- Контракты служб — укажите операции, которые поддерживаются службами, и сообщения, необходимые для взаимодействия с каждой операцией. Service contracts – specify the operations that services support and the messages required for interacting with each operation. Они также указывают любое пользовательское поведение при сбое, которое может быть связано с операциями в каждой службе. They also specify any custom fault behavior that can be associated with operations on each service.
Существуют различия между ASP.NET Web Services (ASMX) и WCF, но важно понимать, что WCF поддерживает те же возможности, которые предоставляет ASMX — сообщения SOAP по протоколу HTTP. There are differences between ASP.NET Web Services (ASMX) and WCF, but it is important to understand that WCF supports the same capabilities that ASMX provides – SOAP messages over HTTP.
Поддержка платформы Xamarin для WCF ограничена текстовыми сообщениями SOAP по протоколу HTTP/HTTPS с помощью BasicHttpBinding класса. The Xamarin platform support for WCF is limited to text-encoded SOAP messages over HTTP/HTTPS using the BasicHttpBinding class. Кроме того, поддержка WCF требует использования средств, доступных только в среде Windows для создания учетной записи-посредника. In addition, WCF support requires the use of tools only available in a Windows environment to generate the proxy.
Создание учетной записи-посредника Generating a Proxy
Для использования службы WCF необходимо создать прокси-сервер , который позволяет приложению подключаться к службе. A proxy must be generated to consume a WCF service, which allows the application to connect to the service. Прокси-сервер создается путем использования метаданных службы, определяющих методы и связанную с ней конфигурацию службы. The proxy is constructed by consuming service metadata that define the methods and associated service configuration. Эти метаданные представлены в виде документа языка описания веб-служб (WSDL), созданного веб-службой. This metadata is exposed in the form of a Web Services Description Language (WSDL) document that is generated by the web service. Прокси-сервер можно построить с помощью Microsoft WCF Web Service Reference Provider в Visual Studio 2017, чтобы добавить ссылку на службу для веб-службы в библиотеку .NET Standard. The proxy can be built by using the Microsoft WCF Web Service Reference Provider in Visual Studio 2017 to add a service reference for the web service to a .NET Standard Library.
Альтернативой созданию прокси-сервера с помощью Microsoft WCF Web Service Reference Provider в Visual Studio 2017 является использование средства служебной программы метаданных ServiceModel (svcutil.exe). An alternative to creating the proxy using the Microsoft WCF Web Service Reference Provider in Visual Studio 2017 is to use the ServiceModel Metadata Utility Tool (svcutil.exe). Дополнительные сведения см. в разделе средство служебной программы метаданных ServiceModel (Svcutil.exe). For more information, see ServiceModel Metadata Utility Tool (Svcutil.exe).
Настройка прокси-сервера Configuring the Proxy
Настройка созданного прокси-сервера обычно принимает два аргумента конфигурации (в зависимости от SOAP 1.1/ASMX или WCF) во время инициализации: EndpointAddress и/или связанные сведения о привязке, как показано в следующем примере: Configuring the generated proxy will generally take two configuration arguments (depending on SOAP 1.1/ASMX or WCF) during initialization: the EndpointAddress and/or the associated binding information, as shown in the example below:
Привязка используется для указания транспорта, кодировки и сведений о протоколе, необходимых приложениям и службам для взаимодействия друг с другом. A binding is used to specify the transport, encoding, and protocol details required for applications and services to communicate with each other. BasicHttpBinding Указывает, что сообщения SOAP, закодированные в виде текста, будут отправляться через транспортный протокол HTTP. The BasicHttpBinding specifies that text-encoded SOAP messages will be sent over the HTTP transport protocol. Указание адреса конечной точки позволяет приложению подключаться к разным экземплярам службы WCF при условии, что существует несколько опубликованных экземпляров. Specifying an endpoint address enables the application to connect to different instances of the WCF service, provided that there are multiple published instances.
Использование прокси-сервера Consuming the Proxy
Созданные классы прокси предоставляют методы для использования веб-служб, использующих шаблон разработки модели асинхронного программирования (APM). The generated proxy classes provide methods for consuming the web services that use the Asynchronous Programming Model (APM) design pattern. В этом шаблоне асинхронная операция реализуется в виде двух методов с именами бегиноператионнаме и ендоператионнаме, которые начинают и завершают асинхронную операцию. In this pattern, an asynchronous operation is implemented as two methods named BeginOperationName and EndOperationName, which begin and end the asynchronous operation.
Метод бегиноператионнаме начинает асинхронную операцию и возвращает объект, реализующий IAsyncResult интерфейс. The BeginOperationName method begins the asynchronous operation and returns an object that implements the IAsyncResult interface. После вызова бегиноператионнамеприложение может продолжить выполнение инструкций в вызывающем потоке, в то время как асинхронная операция выполняется в потоке пула потоков. After calling BeginOperationName, an application can continue executing instructions on the calling thread, while the asynchronous operation takes place on a thread pool thread.
Для каждого вызова бегиноператионнамеприложение должно также вызывать ендоператионнаме для получения результатов операции. For each call to BeginOperationName, the application should also call EndOperationName to get the results of the operation. Возвращаемое значение ендоператионнаме имеет тот же тип, что и синхронный метод веб-службы. The return value of EndOperationName is the same type returned by the synchronous web service method. В следующем коде показан пример такого действия: The following code example shows an example of this:
Библиотека параллельных задач (TPL) может упростить процесс использования пары методов Begin и End APM, инкапсулирующие асинхронные операции в одном Task объекте. The Task Parallel Library (TPL) can simplify the process of consuming an APM begin/end method pair by encapsulating the asynchronous operations in the same Task object. Это инкапсуляция обеспечивается несколькими перегрузками Task.Factory.FromAsync метода. This encapsulation is provided by multiple overloads of the Task.Factory.FromAsync method. Этот метод создает Task , который выполняет TodoServiceClient.EndGetTodoItems метод после TodoServiceClient.BeginGetTodoItems завершения метода с null параметром, указывающим, что данные не передаются в BeginGetTodoItems делегат. This method creates a Task that executes the TodoServiceClient.EndGetTodoItems method once the TodoServiceClient.BeginGetTodoItems method completes, with the null parameter indicating that no data is being passed into the BeginGetTodoItems delegate. Наконец, значение TaskCreationOptions перечисления указывает, что следует использовать поведение по умолчанию для создания и выполнения задач. Finally, the value of the TaskCreationOptions enumeration specifies that the default behavior for the creation and execution of tasks should be used.
Использование безопасности транспорта Using Transport Security
Службы WCF могут применять безопасность транспортного уровня для защиты от перехвата сообщений. WCF Services may employ transport level security to protect against interception of messages. Платформа Xamarin поддерживает привязки, которые используют безопасность на транспортном уровне с помощью SSL. The Xamarin platform supports bindings that employ transport level security using SSL. Однако могут возникнуть ситуации, в которых стеку может потребоваться проверить сертификат, что приводит к непредвиденному поведению. However, there may be cases in which the stack may need to validate the certificate, which results in unanticipated behavior. Проверка может быть переопределена путем регистрации ServerCertificateValidationCallback делегата перед вызовом службы, как показано в следующем примере кода: The validation can be overridden by registering a ServerCertificateValidationCallback delegate before invoking the service, as demonstrated in the following code example:
Это обеспечивает шифрование транспорта при игнорировании проверки сертификата на стороне сервера. This maintains transport encryption while ignoring the server-side certificate validation. Однако этот подход эффективно игнорирует проблемы доверия, связанные с сертификатом, и может быть неуместной. However, this approach effectively disregards the trust concerns associated with the certificate and may not be appropriate. Дополнительные сведения см. в разделе using Trusted корни респектфулли On Mono-Project.com. For more information, see Using Trusted Roots Respectfully on mono-project.com.
Использование безопасности учетных данных клиента Using Client Credential Security
Службы WCF также могут требовать, чтобы клиенты службы прошли проверку подлинности с помощью учетных данных. WCF services may also require the service clients to authenticate using credentials. Платформа Xamarin не поддерживает протокол WS-Security, который позволяет клиентам передавать учетные данные внутри конверта сообщения SOAP. The Xamarin platform does not support the WS-Security Protocol, which allows clients to send credentials inside the SOAP message envelope. Однако платформа Xamarin поддерживает возможность отправки учетных данных обычной проверки подлинности HTTP на сервер, указав соответствующий параметр ClientCredentialType : However, the Xamarin platform does support the ability to send HTTP Basic Authentication credentials to the server by specifying the appropriate ClientCredentialType :
Затем можно указать учетные данные обычной проверки подлинности: Then, basic authentication credentials can be specified:
Дополнительные сведения о обычной проверке подлинности HTTP, хотя в контексте веб-службы RESTFUL, см. в разделе Проверка подлинности веб-службы RESTful. For more information about HTTP basic authentication, although in the context of a REST web service, see Authenticating a RESTful Web Service.