使用 web api 将自定义异常序列化到 JSON

Serialize custom exception to JSON with web api

我需要在我的 WebApi 的输出 json 中显示添加到自定义异常 ModelException 的自定义 属性。所以我创建了自定义异常 class 如下

 [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

感谢@MrinalKamboj

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

  1. 按照我的问题
  2. 实现我的Custom Exception (ModelException)
  3. 根据@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);
             }
        }
    }
    
  4. 注册属性到Web API如下

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

问题的解释

我想更改由 Web API 产生的输出 json 这将不适用于仅实施 ISerializable 我们需要拦截异常并更改 json 使用 HTTPErorr