Detailed error:
The property 'TargetSite' on type 'System.Exception' cannot be serialized because it is decorated with declarative security permission attributes. Consider using imperative asserts or demands in the property accessors.
Solution: System.Exception object can not be serialized to transfer over the HTTP channel. Obviously, we need to provide some mechanism to serialize its state to some transferable medium like string. And on the other end, typically web service, we need to deserialize it back to the exception object.
I have a BaseException class that derives from System.Exception class. It has
a public property called "ExceptionState" that serializes it to Base64String representation. It also has a static method "Reconstruct" that reconstructs it from the Base64String back to the BaseException object.
public class BaseException : Exception, ISerializable
{
//...
string state;
static BinaryFormatter binaryFormatter = new BinaryFormatter();
/// <summary>
/// Persiste BaseException object to the base 64 string. This property returns
/// a string representation of the exception state which could be used to
/// reconstruct this exception if desired. <see cref="Reconstruct"/> method.
/// This property is introduced to fix the following issue:
/// The property 'TargetSite' on type 'System.Exception' cannot be serialized
/// because it is decorated with declarative security permission attributes.
/// Consider using imperative asserts or demands in the property accessors.
/// </summary>
public string ExceptionState
{
get
{
if (state == null)
{
MemoryStream stream = new MemoryStream();
binaryFormatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
state = Convert.ToBase64String(stream.ToArray());
}
return this.state;
}
}
/// <summary>
/// Reconstructs a <c>BaseException</c> from the supplied exceptionState
/// string. <see cref="ExceptionProperty"/> property comments.
/// </summary>
/// <param name="exceptionState">
/// Base 64 string representation of the xception</param>
/// <returns>
/// A reconstructed <c>BaseException</c> object; null if reconstruction failed.
/// </returns>
public static BaseException Reconstruct(string exceptionState)
{
byte [] buffer = Convert.FromBase64String(exceptionState);
Stream stream = new MemoryStream(buffer, 0, buffer.Length, false);
stream.Seek(0, SeekOrigin.Begin);
object obj = binaryFormatter.Deserialize(stream);
return obj as BaseException;
}
}