views:

1826

answers:

4

is there any way to change the way asp.net generates elements in the WSDL generated from a .asmx file? Specifically, it seems to mark all elements minoccurs="0" and there are some elements that I want to be minoccurs="1" (aka required fields). One of these is an argument to the web service (e.g. foo(arg1, arg2) where I want arg2 to be generated in the WSDL as minoccurs="1") the other is a particular field in the class that corresponds to arg1. Do I have to forego auto WSDL generation and take a "contract first" approach?

+3  A: 

I think that the XmlElement(IsNullable = true) attribute will do the job:

using System.Xml.Serialization;

[WebMethod]
public string MyService([XmlElement(IsNullable = true)] string arg)
{
  return "1";
}


EDIT [VB version]

Imports System.Xml.Serialization

Public Function MyService(<XmlElement(IsNullable:=True)> ByVal arg As String) As String
  Return ("1")
End Function
Panos
do you know how you'd do that in VB.NET? I can't seem to find the equivalent expression...
I updated the answer.
Panos
A: 

For object properties:

Using WCF you could set the IsRequired field using the [DataMember] attribute. You will also find that when setting IsRequired = true, the generated WSDL will not contain the minoccurs="x" attribute at all since the default is 1.

[DataContract]
public class WcfObject
{
    [DataMember(IsRequired = true)]
    public ulong ID { get; set; }

    [DataMember]
    public string AnotherField { get; set; }
}
Brendan Kowitz
He asked about "the WSDL generated from a .asmx file".
John Saunders
@John: I'd see WCF as an extremely viable/better/more flexible alternative to asmx. Perhaps this response adds value to those who come across this question and are using WCF. So, I don't see your point.
Brendan Kowitz
+1  A: 

Using XMLElement(IsNullable=true) generates minOccurs=1, but it also generates in WSDL nillable="true", which is undesirable.

A: 

The only way I know of (short of upgrading to WCF) is to use the [XmlSchemaProvider] attribute. This permits you tio indicate a method that will return the schema that will be emitted as part of the WSDL.

By the time you get to this point, you may find it better to simply write your own WSDL, by hand, so you don't have to worry about how to coerce .NET into writing it for you. You would then simply place the WSDL in a known location on a web site (possible the same site as the service), then tell your customers to use http://url/service.wsdl instead of service.asmx?wsdl.

John Saunders