【发布时间】:2014-07-26 02:45:30
【问题描述】:
我们有一个较旧的 ASP.NET WebForms 应用程序,它通过在客户端使用 jQuery $.ajax() 调用来执行 AJAX 请求,调用带有 [WebMethod] 属性的页面代码隐藏中的静态方法。
如果 WebMethod 中发生未处理的异常,它不会触发 Application_Error 事件,因此不会被我们的错误记录器 (ELMAH) 拾取。这是众所周知的,不是问题 - 我们将所有 WebMethod 代码包装在 try-catch 块中,异常情况被手动记录到 ELMAH。
但是,有一个案例让我很困惑。如果将格式错误的 Json 发布到 WebMethod URL,它会在输入我们的代码之前引发异常,我找不到任何方法来捕获它。
例如这个 WebMethod 签名
[WebMethod]
public static string LeWebMethod(string stringParam, int intParam)
通常使用 Json 有效负载调用,例如:
{"stringParam":"oh hai","intParam":37}
我尝试使用 Fiddler 将有效负载编辑为格式错误的 Json:
{"stringParam":"oh hai","intPara
并从JavaScriptObjectDeserializer 收到以下ArgumentException 错误响应发送到客户端(这是在本地运行的简单测试应用程序中,没有自定义错误):
{"Message":"Unterminated string passed in. (32): {\"stringParam\":\"oh hai\",\"intPara","StackTrace":" at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeString()\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeMemberName()\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at
System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at
System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
它仍然没有触发 Application_Error 事件,并且它从未进入我们的代码,因此我们无法自己记录错误。
我发现了一个类似的问题,它得到了指向博客文章“How to create a global exception handler for a Web Service”的指针,但这似乎只对 SOAP Web 服务有效,对 AJAX GET/POST 无效。
在我的情况下是否有类似的方法来附加自定义处理程序?
【问题讨论】:
标签: asp.net ajax error-handling webmethod