Serialize a FaultException of Generic Type

2

We currently have a mechanism of calling our web services in a test page. However, I am trying to look at the better practices of WCF services and using the FaultException.

So there are cases when the FaultException is thrown by our service, I want to serialize the fault as xml and display on the page.

I've looked at the XmlSerializer and DataContractSerializer so far.

So consider the code:

public SomeResponse DoSomething()
{
    throw new FaultException<AuthenticationFault>(
                new AuthenticationFault(), 
                new FaultReason("BooHoo"), 
                new FaultCode("1234"));
}

And the futile attempts at serializing:

DataContractSerializer

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}

XmlSerializer

public string Serialize<TObject>(TObject obj)
{
    if (obj == null)
    {
        return string.Empty;
    }

    XmlSerializer serializer = new XmlSerializer(obj.GetType());
    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), string
        Indent = true,
        OmitXmlDeclaration = true
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, obj);
        }
        return textWriter.ToString();
    }
}

Test Call and Catch

public override string Invoke(string request)
{
    try
    {
        var service = new AcmeService();
        return Serialize(service.DoSomething());
    }
    catch (FaultException ex)
    {
        return Serialize(ex);
    }
}

AuthenticationFault

[DataContract]
public class AuthenticationFault
{
}

Exceptions

The following exceptions are raised in the scenarios above. However, I do appreciate there is no parameterless constructor for the generic FaultException. The runtime must be able to serialize back over the wire.

DataContractSerializer

System.Runtime.Serialization.SerializationException occurred
  HResult=0x8013150C
  Message=Type 'BuyerAcmeApp.Services.Faults.AuthenticationFault' with data contract name 'AuthenticationFault:http://schemas.acme.com/p4/services/2017/11' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

XmlSerializer

System.InvalidOperationException occurred
  HResult=0x80131509
  Message=There was an error reflecting type 'System.ServiceModel.FaultException'.
  Source=App_Code.etbsvkgf
  StackTrace:
   at AcmeApp.WebServices.Tests.WebServiceMethodItem`2.Serialize[TObject](TObject obj) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\App_Code\WebServices\Tests\WebServiceMethodItemBase.cs:line 70
   at AcmeApp.WebServices.Tests.WebServiceMethodItemWithError`2.Invoke(String request) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\App_Code\WebServices\Tests\WebServiceMethodItemBase.cs:line 104
   at AcmeApp.Diagnostics.WebServiceTestPage.CallMethodButton_OnClick(Object sender, EventArgs e) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\Diagnostics\WebServiceTestPage.aspx.cs:line 44

Inner Exception 1:
NotSupportedException: Cannot serialize member System.Exception.Data of type System.Collections.IDictionary, because it implements IDictionary.
c#
asp.net
web-services
wcf
faultexception
asked on Stack Overflow Nov 14, 2017 by Andez • edited Nov 14, 2017 by Andez

1 Answer

1

When serialising, the known types need to be supplied to the DataContractSerializer.

public static string Serialize(object obj)
{
    var settings = new XmlWriterSettings { Indent = true };

    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(
        obj.GetType(), new Type[]
        {
            typeof(AuthenticationFault)
        });

        serializer.WriteObject(memoryStream , obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}
answered on Stack Overflow Nov 15, 2017 by Andez • edited Nov 15, 2017 by Andez

User contributions licensed under CC BY-SA 3.0