title: Return a custom error message in WCF http service
body: <p>I'm just starting out in C# and am a little stuck on this. </p>
  
  <p>I need to return a custom error message when a user doesn't have access to a particular resource.</p>
  
  <p>Interface class for service:</p>
  
  <pre><code>[ServiceContract]
  public interface IPatientDemographics
  {
      [OperationContract]   
      [WebInvoke(Method = "GET", UriTemplate = "GetPatientDemographics/{strHospId}/{strView=mobile}",
      ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
      [return: MessageParameter(Name = "PatientDemographicsResultSet")]
      List&lt;PatientDemographics&gt; GetPatientDemographics(string strHospId, string strView);
  
      [OperationContract]
      [FaultContract(typeof(AccessError))]
      [return: MessageParameter(Name = "Error")]
      AccessError ReturnAccessError();        
  }
  
  [DataContract]
  public class AccessError
  {
      [DataMember]
      public bool Error { get; set; }
      [DataMember]
      public string Message { get; set; }
  }
  </code></pre>
  
  <p>Service class:</p>
  
  <pre><code>[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]
  public class PatientDemographics : IPatientDemographics
  {
      public List&lt;PatientDemographics&gt; GetPatientDemographics(string strHospId, string strView)
      {
          AuthenticationDAO authenticationDAO = new AuthenticationDAO();
          string userName = GetUserNameFromHeader();
  
          if (authenticationDAO.CheckPatientSealAccess(strHospId, userName, "-1", "N"))
          {
              PatientDAO patientDAO = new PatientDAO();
              patientDAO.AuditPatient(strHospId, userName);
              return patientDAO.GetPatientDemographics(strHospId);
          }
          else
          {
              AccessError serviceData = new AccessError();
              serviceData.Error = true;
              serviceData.Message = "User does not have access to patient record";
              throw new FaultException&lt;AccessError&gt;(serviceData, "User does not have access to patient record");
          }
      }
  }
  </code></pre>
  
  <p>At the moment, this just returns a null object if the user doesn't have access. I tried throwing a FaultException but had no luck. Ideally I want it to return in JSON format something like:</p>
  
  <pre><code>{
      error: "User does not have access to patient record"
  } 
  </code></pre>