2
我需要在我的WebApi
的輸出json上顯示添加到自定義異常ModelException
的定製屬性。因此,我創建自定義異常類如下使用web api將自定義異常序列化爲JSON
[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;
}
}
然後添加以下CONFIGRATION我WebApiConfig
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableInterface = true
};
這裏的問題是SerializationInfo
參數的新overidden構造不解僱,新的自定義屬性沒有出現在退回Json
from WebApi
我用來實現相同的一種機制是使用Web API錯誤過濾器,它可以攔截異常調用,並可用於修改Context.Response,並附帶必要的異常信息,請檢查: http:///www.asp.net/web-api/overview/error-handling/exception-handling –
您不需要設置「IgnoreSerializableInterface = false」嗎? – dbc
@dbc是的我試着設置'IgnoreSerializableInterface = false',但沒有任何工作的自定義屬性doesnt apear –