简体   繁体   中英

Data Annotation with WCF

I am creating a WSDl for a client where they will send request and we will do response.Request contains either phone-number or location or both ie at least one is required.WHat is the best way i can enforce restriction here.I heard like we can use dataanotations which i have used in MVC.I tried in WCF, but when i checked in WSDL by right click ->view in browser i cannot see the restion like minoccurs=1 or range which we were seeing in XSD.So my question is Do i need to create seperate XSD and validate the request or do i need to add dataanotations.Can any body tell me some simple steps which i can follow.Here is what i have tried

[DataMember]
        [Required(ErrorMessage = "Name Required")]
        public string Phonenumber
        {
            get
            {
                return this.phonenumber;
            }
            set
            {
                this.phonenumber = value;
            }
        }
        /// <remarks/>
        /// 
        [DataMember]
                [DataMember]
        [Required(ErrorMessage = "Name Required")]
        public string Location
        {
            get
            {
                return this.location;
            }
            set
            {
                this.location = value;
            }
        }

and in wsdl i can see like

<xs:element name="Phonenumber" type="xs:string" nillable="true" minOccurs="0"/>
<xs:element name="Location" type="xs:string" nillable="true" minOccurs="0"/>

WCF does not understand the [Required] attribute (or other attributes from the data annotations namespace). If you want a data member to be required, you can set the IsRequired property in the attribute:

    [DataMember(IsRequired = true)]
    public string Phonenumber
    {
        get
        {
            return this.phonenumber;
        }
        set
        {
            this.phonenumber = value;
        }
    }
    /// <remarks/>
    /// 
    [DataMember(IsRequired = true)]
    public string Location
    {
        get
        {
            return this.location;
        }
        set
        {
            this.location = value;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM