1

Comming from this post, I would like to throw an exception in my WCF webservice if my client sent me a request with a date not having the UTC kind.

I have created the following custom attribute :

public class IsUtcDateTimeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var date = value as DateTime?;
        if (date != null)
        {
            if (date.Value.Kind != DateTimeKind.Utc)
            {
                return new ValidationResult("DateTime is not UTC format");
            }
        }
        return ValidationResult.Success;
    }
}

I have the following datacontract :

[OperationContract]
SaveAgreementResponse SaveAgreement(SaveAgreementRequest request);

[MessageContract(WrapperName = "SaveAgreementRequest", WrapperNamespace = "http://fooo/agreementServices/1")]
public class SaveAgreementRequest
{
    [DataMember(Name = "TechnicalData"), MessageBodyMember(Name = "TechnicalData")]
    public SaveAgreementTechnicalData TechnicalData { get; set; }

    [DataMember(Name = "InsuranceAgreement"), MessageBodyMember(Name = "InsuranceAgreement")]
    public DC.InsuranceAgreement InsuranceAgreement { get; set; }

}

[DataContract()]
public class InsuranceAgreement {

    [DataMember()]
    [IsUtcDateTime]
    public System.Nullable<System.DateTime> creationDate { get; set; }
}

And I have an integration test using Effort with a creationDate of kind local. But unfortunately, when I'm calling the SaveAgreement() operation, the error doesn't throw.

I may need to register somewhere or explicitly called a validation method, but haven't find any documentation related to custom attribute validation on a WCF webservice.

Xavier W.
  • 1,270
  • 3
  • 21
  • 47
  • https://stackoverflow.com/a/9878663/43846 – stuartd Jul 19 '18 at 10:00
  • @stuartd, thank you for your link. I already considered changing the type to `DatetimeOffSet` but it has an impact on the WSDL, and it's not possible for now. I need a way to properly check the `kind` of my `datetime` and throw an exception. – Xavier W. Jul 19 '18 at 10:03
  • How about a [Parameter inspector](https://www.devtrends.co.uk/blog/validating-wcf-service-operations-using-system.componentmodel.dataannotations)? – stuartd Jul 19 '18 at 11:41

0 Answers0