8

I am looking to place attributes on my WCF data contract members to validate string length and possibly use regex for more granular parameter validation.

I can the [Range] attribute for numeric and DateTime values and was wondering if any of you have found any other WCF Data Member attributes I can use for data validation. I have found a bevvy of attributes for Silverlight but not for WCF.

Jessica
  • 101
  • 1
  • 1
  • 3
  • Possible duplicate of: http://stackoverflow.com/questions/10835455/how-should-i-validate-parameters-passed-into-my-wcf-service/10839767#10839767 – ErnieL Oct 15 '12 at 14:48

3 Answers3

22

Add System.ComponentModel.DataAnnotations reference to your project.

The reference provides some DataAnnotations which are:

RequiredAttribute, RangeAttribute, StringLengthAttribute, RegularExpressionAttribute

you can in your datacontract like below.

    [DataMember]
    [StringLength(100, MinimumLength= 10, ErrorMessage="String length should be between 10 and 100." )]
    [StringLength(50)]     // Another way... String max length 50
    public string FirstName { get; set; }

    [DataMember]
    [Range(2, 100)]
    public int Age { get; set; }

    [DataMember]
    [Required]
    [RegularExpression(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", ErrorMessage = "Invalid Mail id")]
    public string Email { get; set; }

Hope this helps.

Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
  • 14
    This is nice, but how do I get my web service to enforce these restrictions? When I debug, and pass in bad data (or missing data) it still does not throw any errors. – MikeTeeVee Jun 27 '13 at 15:27
  • 2
    @MikeTeeVee you can do it by using IParameterInspector. See this http://www.devtrends.co.uk/blog/validating-wcf-service-operations-using-system.componentmodel.dataannotations – Prasad Kanaparthi Nov 18 '14 at 09:39
2

Manually Validating Values: You can manually apply the validation test by using the Validator class. You can call the ValidateProperty method on the set accessor of a property to check the value against the validation attributes for the property. You must also set both ValidatesOnExceptions and NotifyOnValidationError properties to true when data binding to receive validation exceptions from validation attributes.

var unsafeContact = Request["contactJSON"];
try
{
    var serializer = new DataContractJsonSerializer(typeof(Contact));
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(unsafeContact));
    Contact = serializer.ReadObject(stream) as Contact;
    stream.Close();
}
catch (Exception)
{
   // invalid contact
}

Contact class:

[DataContract]
public sealed class Contact
{
    /// <summary>
    /// Contact Full Name
    /// </summary>
    /// <example>John Doe</example>
    [DataMember(Name = "name", IsRequired = true)]
    [StringLength(100, MinimumLength = 1, ErrorMessage = @"Name length should be between 1 and 100.")]
    public string Name {
        get
        {
            return HttpUtility.HtmlEncode(_name);
        }
        internal set
        {
            Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name" });
            _name = value;
        }
    }
    private string _name;

    // ...
}
SavoryBytes
  • 35,571
  • 4
  • 52
  • 61
1

Try to look look for WCF Data Annotations. WCFDataAnnotations allows you to automatically validate WCF service operation arguments using System.ComponentModel.DataAnnotations attributes.

http://wcfdataannotations.codeplex.com/

Milan Matějka
  • 2,654
  • 1
  • 21
  • 23
  • I added DevTrends.WCFDataAnnotations in wcf,and DataAnnotations validation error is able to pass at client .But whenver there is validation error,exception is thrown at client end.I want to stop this.I want some "HasError" to be true and there is no exception.How to do this. Thanks – KumarHarsh Dec 18 '14 at 11:11