使用Web API将自定义异常序列化为JSON

3

我需要在我的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,并提供必要的异常信息。请参考以下链接:http://www.asp.net/web-api/overview/error-handling/exception-handling - Mrinal Kamboj
难道你不需要将 IgnoreSerializableInterface = false 设置为否吗? - dbc
@dbc 是的,我尝试将 IgnoreSerializableInterface = false,但是没有效果,自定义属性没有出现。 - Mohamed Salah
@MrinalKamboj 我尝试添加自定义过滤器来拦截异常调用,但是没有成功在最终的JSON中显示自定义属性。 - Mohamed Salah
1个回答

5

感谢@MrinalKamboj提供的帮助。

为了在异常情况下更改Web API的输出Json,我做了以下更改来解决这个问题。

  1. Implement my Custom Exception (ModelException) as in my Question
  2. as per @MrinalKamboj comment i created the following

    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. register the attribute to Web API as follows

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

问题的解释

我想改变从Web API结果输出的json,但仅通过实现ISerializable是不可行的,我们需要拦截异常并使用HTTPErorr更改json的输出响应。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接