title: Creating a WCF webservice with a single standard response object
body: <p>I've been asked to implement a webservice using WCF that will return a single standard response object that indicates whether the webservice call succeeds or fails and an error message if one occurs. </p>
  
  <p>It looks to me like this is not how WCF is intended to be used, is that correct? </p>
  
  <p>My problem is that I am using IDispatchMessageInspector.AfterReceiveRequest() to validate the request against an XSD prior to WCF deserializing it and calling my operation.</p>
  
  <p>If it fails validation how do I return my standard response object? WCF seems to want me to throw a FaultException in this scenario but I want the interface to purely return one standard response object that contains any failure information.</p>
  
  <p>So this would mean that you need to define both a custom Fault Exception that you can throw when the request you receive fails validation prior to deserialization etc, and the second standard response to send when the request succeeds. </p>
  
  <p>Is that the right approach?</p>
  
  <p>To achieve my goal of simply returning the one single response object if something like a validation error occurs, I've been trying to cheat and set the request object to null in AfterReceiveRequest() so it skips processing of the request.</p>
  
  <pre><code> object IDispatchMessageInspector.AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
          {
              try
              {
                  validateMessage(ref request);
              }
              catch (Exception e)
              {
                  request = null;
                  return new FaultException&lt;string&gt;(e.Message);
              }
              return null;
  
          }
  </code></pre>
  
  <p>and then perhaps I can create my own custom response object in BeforeSendReply(). </p>
  
  <pre><code> void IDispatchMessageInspector.BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
          {
              if (correlationState != null)
              {
                  reply = CreateMyOwnResponse(((FaultException) correlationState));
              }
          }
  </code></pre>
  
  <p>But I know that this seems silly and is working against how WCF is meant to be used most likely. Is there a way to nicely achieve what I want or do I have to send an exception type when things go bad and a different "normal" response when things succeed?</p>