views:

52

answers:

1

When using WCF together with Enterprise Library 5.0's validation application block, is it possible to customize the error messages which are sent back to the client?

I've added the ValidationBehaviour-attribute to my service contract and the FaultContract-attribute to the operation:

<ServiceContract()> _
<ValidationBehavior()> _
Public Interface IContract

    <OperationContract(), FaultContract(GetType(ValidationFault))> _
    Function GetCustomers(ByVal criteria As CustomersSearchCriteria) As List(Of Customer)

End Interface

Then, inside the CustomersSearchCriteria I've added the validation attributes:

<Validators.StringLengthValidator(1, 3, ErrorMessage:="here's my error", Tag:="551")> _
Public Property Pin() As String
    Get
        Return _pin
    End Get
    Set(ByVal value As String)
        _pin = value
    End Set
End Property

But when called with invalid parameter, the returned SOAP looks like this:

  <s:Fault>
     <faultcode>s:Client</faultcode>
     <faultstring xml:lang="fi-FI">The creator of this fault did not specify a Reason.</faultstring>
     <detail>
        <ValidationFault xmlns="http://www.microsoft.com/practices/EnterpriseLibrary/2007/01/wcf/validation" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;
           <Details xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF"&gt;
              <a:ValidationDetail>
                 <a:Key>Pin</a:Key>
                 <a:Message>The length of the value must fall within the range "1" (Inclusive) - "3" (Inclusive).</a:Message>
                 <a:Tag>criteria</a:Tag>
              </a:ValidationDetail>
           </Details>
        </ValidationFault>
     </detail>
  </s:Fault>

The service returns ValidationFault as it should, but instead of having the error message and tag which I've defined, it uses some generic values. Is this a bug or am I doing something wrong?

+2  A: 

I think you need to use the MessageTemplate property instead of the ErrorMessage property. Try:

<Validators.StringLengthValidatorAttribute(1, 3, MessageTemplate:="here's my error", Tag:="551")> _
Tuzo
Tuzo is absolutely right. `ErrorMessage` is a property that is defined by DataAnnotations. Attributes in VAB 5.0 now inherit from DataAnnotations' attributes and therefore also have this property. I don't really understand why they didn't allow users to also use the `ErrorMessage` property.
Steven
@Steven, I agree with you -- the EL 5.0 implementation is confusing. My only guess they wanted to be backward compatible.
Tuzo