Asp.net Web 方法 ajax 调用显示堆栈跟踪和实际异常,而自定义错误模式打开



我正在使用ajax调用调用Web方法。下面是示例调用。

[WebMethod(true)]
public static string Save(string customParams)
{
throw new ApplicationException("Example Exception");
}
$.ajax({
url: url,
type: "POST",
data: data,
contentType:"application/json; charset=utf-8",
dataType: props.dataType ? props.dataType : "text",
error: function (xhr, errorType, ex) {
debugger;
err(ex);
}
})

如果该方法引发异常,我只会收到 500 内部服务器错误。堆栈跟踪为空,我无法收到内部异常消息。我用尝试捕获块装饰了网络方法并返回 HttpException 并设置它的文本,但它不起作用。

try
{
throw new ApplicationException("Example Exception");
}
catch (Exception e)
{
throw new HttpException(500,e.Message,e);
}

我也再次尝试了这个解决方案,但没有运气。

catch (Exception e)
{
HttpContext.Current.Response.Write(e.Message.ToJsonString());
HttpContext.Current.Response.StatusCode=500;
}

顺便说一下,我还尝试了当请求是ajax请求时未捕获的异常无法被Global.asax的Application_Error捕获.这就是问题所在。 我关闭了自定义错误。现在它显示错误,但仍然不是有意的解决方案。

任何解决方案?提前谢谢。

我找到了实现这一点的方法。您可能会注意到,我正在更改 500 错误响应文本,其中包含实际异常的消息和堆栈跟踪。

首先清除响应和标头。然后设置 TrySkipIisCustomErrors = true,以便不让 asp.net 返回 500 错误页面。之后将实际错误消息写入响应,刷新它并结束处理页面。我真的不知道这是理想的方式,但到目前为止,我只得到了这个解决方案。

这是代码。

public static string ProcessAjaxException(Exception ex)
{
if (!HttpContext.Current.Request.IsAjaxRequest())
{
return null;
}
var page = (Page)HttpContext.Current.CurrentHandler;
string url = page.AppRelativeVirtualPath;
Framework.Core.Logging.LoggerFactory.Error(url, ex);
var jsonExceptionDetails = new { ex.Message, ex.StackTrace, statusText = "500" };
var serializedExcpDetails = JsonConvert.SerializeObject(jsonExceptionDetails);
//Erases any buffered HTML output.
HttpContext.Current.Response.Clear();
//Erases header
HttpContext.Current.Response.ClearHeaders();
/*If the IHttpResponse::SetStatus method was called by using the fTrySkipCustomErrors flag, 
* the existing response is passed through, 
* and no detailed or custom error is shown.*/
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.StatusCode = 500;
//Send all buffered output to client 
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Write(serializedExcpDetails);
//Stop processing the page
HttpContext.Current.Response.End();
return null;
}

最新更新