Search code examples
c#asp.netweb-serviceswcffaultexception

WCF Client not able to see Custom Fault Exception


as you can probably make out from the question title that I am new to WCF. I have implemented this web service and one of the methods throws a custom FaultException.

namespace Feed
{
    [ServiceContract]
    public interface IMyClass
    {
        [OperationContract]
        [FaultContract(typeof(CustomError))]
        DataSet MyMethod(int A, int T);
    }
    [DataContract]
    public class CustomError
    {
        public CustomError(string msg, int code, int id)
        {
            Id = id;
            ErrorMessage = msg;
            ErrorCode = code;
        }
        [DataMember]
        [DataMember]
        public string ErrorMessage
        {
            get;
            set;
        }

        [DataMember]
        public int ErrorCode
        {
            get;
            set;
        }

        [DataMember]
        public int Id
        {
            get;
            set;
        }
    }
}

Then, I throw the proper exception in the implementation of MyMethod

namespace Feeds
{
    public class MyClass : IMyClass
    {
        DataSet MyMethod(int A, int T)
        {
            try
            {
                //todo
                DataSet ds = new DataSet();
                return ds;
            }
            catch (Exception ex)
            {
                throw new FaultException<CustomError>(new CustomError("a", 1, 0));
            }
        }
    }
}

So far so good. Now I created a simple ASP.NET website which consumes this web service. I added a WebReference in that website for the MyClass.svc web service. Problem is that when I'm trying to catch the exception: catch(FaultException ex) { } it is not able to recognize CustomError. I have done the following troubleshooting: 1. Ensure I have the wsdl updated (done numerous time, tried changing other things, everything is reflected on the client side) 2. Tried BasicHttpBinding as well as wsHttpBinding (not sure if that makes a difference) 3. Googled alot and followed sample code from MSDN religiously.

Still no luck! Am I missing something? Any suggestions will be greatly appreciated.


Solution

  • Found out what the problem is.
    My ASP.NET website was on .NET Framework 2.0 (which is what VS 2010 does by default), and I was adding the reference to the web service by right-clicking the project and selecting "Add Web Reference..".
    However, what I needed to do what, select "Add Service Reference.." to add the web service as a service reference. Since .NET 2.0 does not support service references, I had to upgrade my .NET framework to 3.5, add the service reference and everything worked like a charm! This post lighted the bulb in my mind. Thanks everyone for all the effort put into this.