【问题标题】:Serialize custom exception to JSON with web api使用 web api 将自定义异常序列化为 JSON
【发布时间】: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


【解决方案1】:

感谢@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());
    

问题说明

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

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多