Check if actual null value was passed to a datamember in wcf

452 views Asked by At

By default all the data member values in a parameter object to wcf service will be null. But how to check if actual null value was passed from the client to my service.

In otherwords if the client actually passed any values including null values to datamembers then I have to do some DB operations. So I need to distinguish between default null values and actual null values passed by client. Please advice.

2

There are 2 answers

0
Mohammad On

I'm not sure this is what you asked but you can implement something like this in order to null check.

        private bool HasNull(object webServiceInput, string[] optionalParameters = null)
    {
        if (ReferenceEquals(null, webServiceInput))
            return false;

        if (optionalParameters == null)
            optionalParameters = new string[0];

        var binding = BindingFlags.Instance | BindingFlags.Public;
        var properties = webServiceInput.GetType().GetProperties(binding);
        foreach (var property in properties)
        {
            if (!property.CanRead)
                continue;

            if (property.PropertyType.IsValueType)
                continue;

            if (optionalParameters.Contains(property.Name))
                continue;

            var value = property.GetValue(webServiceInput);
            if (ReferenceEquals(null, value))
                return false;
        }

        return true;
    }
0
Igor Labutin On

I think the only solution is to have extra data members following this pattern:

class Contract
{
  [DataMember]
  private string _field;

  public string Field
  {
    get {
      return _field;
    }
    set {
      _field = value;
      FieldSpecified = true;
    }
  }

  [DataMember]
  public string FieldSpecified;
}

This is the pattern that XML serialization uses.