ASMX web service Enum not retaining its value

2019-08-13 20:08发布

问题:

I have created a web service containing an enum with values as follows

public enum DesignChoice
{            
    DesignerChoice = 1,
    CustomerChoice = 2,
    AdditionalDesign=3,
}

When I add a reference to my client website, enum values are changed as in the following code:

(int)DesignChoice.AdditionalDesign returns 2 but I am expecting it to be 3.

I have tried the serialization attributes [System.Xml.Serialization.XmlTypeAttribute()] out of nowhere but had no luck.

WSDL of the service describes the enum as follows:

 <s:simpleType name="DesignChoice">
        <s:restriction base="s:string">
          <s:enumeration value="DesignerChoice" />
          <s:enumeration value="CustomerChoice" />
          <s:enumeration value="AdditionalDesign" />
        </s:restriction>
      </s:simpleType>

When I press F12 on class name in VS it shows me the following code generated from meta data:

public enum DesignChoice
    {
        DesignerChoice = 0,
        CustomerChoice = 1,
        AdditionalDesign = 2,
    }

I am using Visual Studio 2005 and .NET 2.0.

回答1:

Here is the detail explanation what's going on

http://www.kerrywong.com/2006/11/09/be-careful-when-using-enums-in-web-services/



回答2:

The values sent to and from your service will be the string that represents your Enum, for example <DesignChoice>CustomerChoice</DesignChoice>.

The value of this within your service should be correct but as the numerical information on any client may be different, the value on the client could be anything. As long as they send back the correct string value, this shouldn't matter. If the client is relying on the numbering explicitly, there is probably a design flaw in the client, or your service is expecting the integer for a call when it should expect the Enum.