MessageParameterAttribute Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Управляет именем запроса и именами параметров ответа. Не может использоваться с Message или контрактами сообщений.
public ref class MessageParameterAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, Inherited=false)]
public sealed class MessageParameterAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, Inherited=false)>]
type MessageParameterAttribute = class
inherit Attribute
Public NotInheritable Class MessageParameterAttribute
Inherits Attribute
- Наследование
- Атрибуты
Примеры
В следующем примере кода показано использование атрибута MessageParameterAttribute для задания имени параметра и возвращаемого значения в метаданных.
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;
namespace Microsoft.WCF.Documentation
{
[ServiceContract(Namespace="http://microsoft.wcf.documentation")]
public interface ISampleService{
[OperationContract]
[return:MessageParameter(Name = "Output")]
string SampleMethod([MessageParameter(Name = "Input")]string msg);
}
/*
The preceding use of MessageParameterAttribute generates the following XSD:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema
elementFormDefault="qualified"
targetNamespace="http://microsoft.wcf.documentation"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://microsoft.wcf.documentation">
<xs:element name="SampleMethod">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="Input" nillable="true" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SampleMethodResponse">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="Output" nillable="true" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
And the message sent is edited for clarity:
<s:Body>
<SampleMethod xmlns="http://microsoft.wcf.documentation">
<Input>hello!</Input>
</SampleMethod>
</s:Body>
*/
Imports System.ServiceModel
Imports System.Text
Namespace Microsoft.WCF.Documentation
<ServiceContract(Namespace:="http://microsoft.wcf.documentation")> _
Public Interface ISampleService
<OperationContract> _
Function SampleMethod(<MessageParameter(Name := "Input")> ByVal msg As String) As <MessageParameter(Name := "Output")> String
End Interface
'
' The preceding use of MessageParameterAttribute generates the following XSD:
'
'<?xml version="1.0" encoding="utf-8" ?>
' <xs:schema
' elementFormDefault="qualified"
' targetNamespace="http://microsoft.wcf.documentation"
' xmlns:xs="http://www.w3.org/2001/XMLSchema"
' xmlns:tns="http://microsoft.wcf.documentation">
' <xs:element name="SampleMethod">
' <xs:complexType>
' <xs:sequence>
' <xs:element minOccurs="0" name="Input" nillable="true" type="xs:string" />
' </xs:sequence>
' </xs:complexType>
' </xs:element>
' <xs:element name="SampleMethodResponse">
' <xs:complexType>
' <xs:sequence>
' <xs:element minOccurs="0" name="Output" nillable="true" type="xs:string" />
' </xs:sequence>
' </xs:complexType>
' </xs:element>
' </xs:schema>
'
' And the message sent is edited for clarity:
' <s:Body>
' <SampleMethod xmlns="http://microsoft.wcf.documentation">
' <Input>hello!</Input>
' </s:Body>
'
В следующем примере показан созданный контракт службы для предыдущей службы. Обратите внимание, что имя параметра теперь — Input
.
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://microsoft.wcf.documentation", ConfigurationName="ISampleService")]
public interface ISampleService
{
[System.ServiceModel.OperationContractAttribute(
Action="http://microsoft.wcf.documentation/ISampleService/SampleMethod",
ReplyAction="http://microsoft.wcf.documentation/ISampleService/SampleMethodResponse"
)]
[return: System.ServiceModel.MessageParameterAttribute(Name="Output")]
string SampleMethod(string Input);
}
<System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0"), _
System.ServiceModel.ServiceContractAttribute(Namespace:="http://microsoft.wcf.documentation", _
ConfigurationName:="ISampleService")> _
Public Interface ISampleService
<System.ServiceModel.OperationContractAttribute(Action:="http://microsoft.wcf.documentation/ISampleService/SampleMethod", _
ReplyAction:="http://microsoft.wcf.documentation/ISampleService/SampleMethodResponse")> _
Function SampleMethod(ByVal Input As String) As <System.ServiceModel.MessageParameterAttribute(Name:="Output")> String
End Interface
Комментарии
Используйте атрибут MessageParameterAttribute для управления именем параметра или возвращаемым значением. Этот атрибут не действует, если параметры отмечены атрибутом MessageContractAttribute.
Примечание
Значения имен параметров в сигнатуре операции являются частью контракта и чувствительны к регистру. Используйте этот атрибут, когда требуется различать имя локального параметра и метаданные, описывающие операцию для клиентских приложений.
Дополнительные сведения об управлении сериализацией содержимого текста SOAP без изменения самого конверта SOAP по умолчанию см. в разделах System.Runtime.Serialization.DataContractAttribute, Указание передачи данных в контрактах служб и Использование контрактов данных.
Дополнительные сведения о создании контрактов сообщений см. в разделе Использование контрактов сообщений.
Конструкторы
Message |
Инициализирует новый экземпляр класса MessageParameterAttribute. |
Свойства
Name |
Возвращает или задает атрибут имени параметра в схеме XML (XSD). |
Type |
В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute. (Унаследовано от Attribute) |
Методы
Equals(Object) |
Возвращает значение, показывающее, равен ли экземпляр указанному объекту. (Унаследовано от Attribute) |
Get |
Возвращает хэш-код данного экземпляра. (Унаследовано от Attribute) |
Get |
Возвращает объект Type для текущего экземпляра. (Унаследовано от Object) |
Is |
При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса. (Унаследовано от Attribute) |
Match(Object) |
При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту. (Унаследовано от Attribute) |
Memberwise |
Создает неполную копию текущего объекта Object. (Унаследовано от Object) |
To |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
_Attribute. |
Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. (Унаследовано от Attribute) |
_Attribute. |
Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса. (Унаследовано от Attribute) |
_Attribute. |
Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). (Унаследовано от Attribute) |
_Attribute. |
Предоставляет доступ к открытым свойствам и методам объекта. (Унаследовано от Attribute) |
Применяется к
Продукт | Версии |
---|---|
.NET | Core 1.0, Core 1.1, 8 (package-provided), 9 (package-provided), 10 (package-provided) |
.NET Framework | 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 2.0 (package-provided) |
UWP | 10.0 |