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
Атрибуты

Примеры

В следующем примере кода показано использование атрибута 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, Указание передачи данных в контрактах служб и Использование контрактов данных.

Дополнительные сведения о создании контрактов сообщений см. в разделе Использование контрактов сообщений.

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

MessageParameterAttribute()

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

Свойства

Name

Возвращает или задает атрибут имени параметра в схеме XML (XSD).

TypeId

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

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

Методы

Equals(Object)

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

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

Возвращает хэш-код данного экземпляра.

(Унаследовано от Attribute)
GetType()

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

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

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

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

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

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

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

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

Возвращает строку, представляющую текущий объект.

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

Явные реализации интерфейса

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

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

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

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

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.

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

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