Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a parameter of an OperationContract as required

I wonder how I can specify a parameter of an OperationContract method in WCF as required so that the generated xsd contains minOccurs="1" instead of minOccurs="0".

Example:

[ServiceContract(Namespace = "http://myUrl.com")]  
public interface IMyWebService  
{  
   [OperationContract]  
   string DoSomething(string param1, string param2, string param3);  
}

generates this xsd:

<xs:element name="DoSomething">  
  <xs:complexType>  
    <xs:sequence>  
      <xs:element minOccurs="0" name="param1" nillable="true" type="xs:string" />  
      <xs:element minOccurs="0" name="param2" nillable="true" type="xs:string" />  
      <xs:element minOccurs="0" name="param3" nillable="true" type="xs:string" />  
    </xs:sequence>  
  </xs:complexType>  

But I want to define minOccurs="1" within the code without the necessity to manually fix it in the xsd file.

like image 879
Jan-Patrick Ahnen Avatar asked Aug 04 '10 14:08

Jan-Patrick Ahnen


People also ask

How do I use OperationContract?

[OperationContract] attribute is used to define the methods of service contract. This attribute is placed on methods that you want to include as a part of service contract. Only those methods that are marked with OperationContract attribute are exposed to client.

What is OperationContractAttribute?

The OperationContractAttribute attribute declares that a method is an operation in a service contract. Only methods attributed with the OperationContractAttribute are exposed as service operations.

What is Operation contract in WCF?

An Operation Contract defines the method exposed to the client to exchange the information between the client and server. An Operation Contract describes what functionality is to be given to the client, such as addition, subtraction and so on. It can be defined as in the following: public interface IService1.


2 Answers

You might need to wrap your parameters in a class, then you can use the DataMember attribute and specify IsRequired=true:

[ServiceContract(Namespace = "http://myUrl.com")]  
public interface IMyWebService  
{  
   [OperationContract]  
   string DoSomething(RequestMessage request);  
}

[DataContract]
public class RequestMessage
{
   [DataMember(IsRequired = true)]
   public string param1 { get; set; }

   [DataMember(IsRequired = true)]
   public string param3 { get; set; }

   [DataMember(IsRequired = true)]
   public string param3 { get; set; }
}
like image 122
Graham Clark Avatar answered Sep 27 '22 21:09

Graham Clark


This implementation is nice to me: http://thorarin.net/blog/post/2010/08/08/Controlling-WSDL-minOccurs-with-WCF.aspx

like image 40
Pit Ming Avatar answered Sep 27 '22 21:09

Pit Ming