I need to show custom property added to custom exception ModelException at the output json of my WebApi. So I created custom exception class as follows
[Serializable]
public class ModelException : System.Exception
{
private int exceptionCode;
public int ExceptionCode
{
get
{
return exceptionCode;
}
set
{
exceptionCode = value;
}
}
public ModelException() : base() { }
public ModelException(string message) : base(message) { }
public ModelException(string format, params object[] args) : base(string.Format(format, args)) { }
public ModelException(string message, System.Exception innerException) : base(message, innerException) { }
public ModelException(string format, System.Exception innerException, params object[] args) : base(string.Format(format, args), innerException) { }
protected ModelException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
int result = 0;
int.TryParse(info.GetString("ExceptionCode"), out result);
this.exceptionCode = result;
}
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("ExceptionCode", this.exceptionCode);
}
base.GetObjectData(info, context);
}
public ModelException(string message, int exceptionCode)
: base(message)
{
this.exceptionCode = exceptionCode;
}
}
then add the following configration to my WebApiConfig
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableInterface = true
};
the issue here is the new overidden constructor with SerializationInfo parameter is not fired and the newly custom property is not appear in the returned Json from WebApi
IgnoreSerializableInterface = falseinstead?IgnoreSerializableInterface = falsebut nothing worked the custom property doesnt apear