使用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

+0

我用来实现相同的一种机制是使用Web API错误过滤器,它可以拦截异常调用,并可用于修改Context.Response,并附带必要的异常信息,请检查: http:///www.asp.net/web-api/overview/error-handling/exception-handling –

+0

您不需要设置“IgnoreSerializableInterface = false”吗? – dbc

+0

@dbc是的我试着设置'IgnoreSerializableInterface = false',但没有任何工作的自定义属性doesnt apear –

感谢@MrinalKamboj

为了在Exception的情况下更改Web API的输出Json。我做了以下修改来解决这个

  1. 实现我Custom Exception (ModelException)在我的问题
  2. 按@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); 
         } 
        } 
    } 
    
  3. 属性寄存器Web API如下

    config.Filters.Add(new NotImplExceptionFilterAttribute()); 
    

这不会是适用的只是实现ISerializable我们需要拦截异常,并使用改变JSON的输出响应的问题

我想改变输出json源于Web API的解释HTTPErorr