简体   繁体   English

如何在c#中将自定义异常序列化为json

[英]How to serialize a custom exception to json in c#

I have ac# web service that I call using jquery ajax. 我有一个ac #web服务,我用jquery ajax调用。 It works fine except when a custom exception is throw inside the web method. 它工作正常,除非在Web方法中抛出自定义异常。 For some reason, the XmlHttpResponse objects responseText only has the base Exception class's properties. 出于某种原因,XmlHttpResponse对象responseText仅具有基本Exception类的属性。 So I end up with a json object with the following properties: "ExceptionType", "Message", and "StackTrace" 所以我最终得到了一个具有以下属性的json对象:“ExceptionType”,“Message”和“StackTrace”

My custom exception has a property called "FieldErrors" that doesn't not show up in the return. 我的自定义异常有一个名为“FieldErrors”的属性,该属性在返回时不会显示。 Here's the code for that class: 这是该类的代码:

[Serializable]
[XmlRootAttribute(Namespace = "http://www.mydomain.com/", IsNullable = false)]
public class ValidationException : Exception
{
    public List<string> FieldErrors { get; set; }
    public ValidationException(string message = null, Exception innerException = null) : base(message: message, innerException: innerException) 
    {
        this.FieldErrors = new List<string>();
    }
}

My goal is to get the "FieldErrors" property to show up in the json response. 我的目标是让“FieldErrors”属性显示在json响应中。

Don't do this. 不要这样做。 You should never expose exceptions from your asp.net site. 你永远不应该暴露你的asp.net网站的异常。

Even if it will end up hidden to the user, you are still sending it with all its detail to the client. 即使它最终会隐藏给用户,您仍然会将其所有细节发送给客户端。

In this case you actually want to control what will be sent, so explicitly sending the list of field errors without sending the json version of the whole exception instance is what you should be doing anyway. 在这种情况下,您实际上想要控制将要发送的内容,因此显式发送字段错误列表而不发送整个异常实例的json版本是您应该做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM