Monday, January 7, 2013

Null MessageBodyMember for WCF Stream Response

If you are using a WCF MessageContract that contains a MessageBodyMember of type Stream, as shown below, the Stream can never be null.

[MessageContract(WrapperNamespace = "")]
public class CreateCertificateResponse : BaseResponseMessageContract, IDisposable

    [MessageHeader(Namespace = "")]
    public long FileLength { get; set; }

    [MessageBodyMember(Order = 1, Namespace = "")]
    public Stream CertificatePDF { get; set; }

    public void Dispose()
        if (this.CertificatePDF != null)
            this.CertificatePDF = null;

If it is null when the response is sent back, then the connection will be closed improperly with a The socket connection was aborted error message.

If you must support a null Stream in the response, you can make use of the System.IO.Stream.Null value. That object is internal, called NullStream and inherits from Stream.