使用web api将自定义异常序列化为JSON
问题描述:
我需要在我的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
答
感谢@MrinalKamboj
为了在Exception
的情况下更改Web API
的输出Json。我做了以下修改来解决这个
- 实现我
Custom Exception (ModelException)
在我的问题 -
按@MrinalKamboj评论我创建了以下
public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is ModelException) { ModelException exception = (ModelException)context.Exception; HttpError error = new HttpError(); error.Add("Message", "An error has occurred."); error.Add("ExceptionMessage", exception.Message); error.Add("ExceptionCode", exception.ExceptionCode); error.Add("ExceptionType", exception.Source); error.Add("StackTrace", exception.StackTrace); context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } } }
-
属性寄存器
Web API
如下config.Filters.Add(new NotImplExceptionFilterAttribute());
这不会是适用的只是实现ISerializable
我们需要拦截异常,并使用改变JSON的输出响应的问题
我想改变输出json
源于Web API
的解释HTTPErorr
我用来实现相同的一种机制是使用Web API错误过滤器,它可以拦截异常调用,并可用于修改Context.Response,并附带必要的异常信息,请检查: http:///www.asp.net/web-api/overview/error-handling/exception-handling –
您不需要设置“IgnoreSerializableInterface = false”吗? – dbc
@dbc是的我试着设置'IgnoreSerializableInterface = false',但没有任何工作的自定义属性doesnt apear –