问题
I'm getting the following exception trying to pass an object through wcf:
There was an error while trying to serialize parameter http://tempuri.org/:item. The InnerException message was 'Enum value '-1' is invalid for type 'Models.SubModels.DamageLocations' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.'. Please see InnerException for more details.
It is defined like:
[DataContract]
public class Property
{
[DataMember]
public PropertyDamage Damage { get; set; }
public Property()
{
this.Damage = new PropertyDamage();
}
}
And PropertyDamage
:
[DataContract]
public enum DamageLocations
{
[EnumMember]
Unknown=0,
[EnumMember]
Front,
[EnumMember]
Rear
}
[DataContract]
public class PropertyDamage
{
[Display(Name="Location of Damage:")]
[DataMember(IsRequired=true)]
public DamageLocations DamageLocation { get; set; }
}
edit - this also causes the same error:
public enum DamageLocations
{
Unknown=0,
Front=1,
Rear=2
}
edit 2- Adding a default value for the enum in the ctor did not change the error:
public PropertyDamage()
{
this.DamageLocation = DamageLocations.Unknown; //0
}
Trying to research the problem, I see people getting a similiar error "Enum value '0' is invalid", and the solution was to add a 0 to the enum.
I already have a 0 item though, and the error states -1 is invalid.
What is the proper way to resolve this?
edit3 - It appears the -1's are coming from the post data, this is the post data from submitting the page.
Damage.DamageLocation=-1
回答1:
It sounds simply like your data has the value -1.
Enums are just fancy integers. You can assign any value to an enum (within the range of the underlying type); for example:
enum Foo { Bar = 1 }
...
Foo foo = (Foo)1035; // perfectly fine
This is fine in c# but not in most serialization libraries, especially those which want to encode it as names (XmlSerializer, DataContractSerializer, etc).
So: if -1 is not a defined value of your enums, don't use that value in your data. If -1 has a meaning, define it in the enum.
回答2:
Change enum DamageLocations{...}
to enum DamageLocations:int
then try.
来源:https://stackoverflow.com/questions/8913631/wcf-datacontract-class-with-enum-causes-enum-value-1-is-invalid-for-type-e