【发布时间】:2016-07-05 09:10:14
【问题描述】:
我需要在我的WebApi 的输出 json 中显示添加到自定义异常 ModelException 的自定义属性。所以我创建了自定义异常类如下
[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;
}
}
然后将以下配置添加到我的WebApiConfig
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableInterface = true
};
这里的问题是没有触发带有SerializationInfo 参数的新的覆盖构造函数,并且新的自定义属性没有出现在从WebApi 返回的Json 中
【问题讨论】:
-
我用来实现相同目的的机制之一是使用 Web API 错误过滤器,它可以拦截对异常的调用,并可用于修改 Context.Response,以及必要的异常信息,检查:asp.net/web-api/overview/error-handling/exception-handling
-
不需要设置
IgnoreSerializableInterface = false吗? -
@dbc 是的,我尝试设置
IgnoreSerializableInterface = false,但没有任何效果,自定义属性没有出现 -
@MrinalKamboj 我尝试添加自定义过滤器来拦截异常调用,但没有运气在最终的 json 中显示自定义属性
标签: c# json asp.net-web-api custom-errors