在ASP.MVC,如何放在ViewData的异常的JavaScript友好的堆栈跟踪? [英] In ASP.MVC, how to place JavaScript-friendly Stack trace of exceptions in ViewData?
问题描述
当任何异常的ASP.MVC服务器端code时,我想借此在ViewData的异常和地点,并返回给客户端的整个堆栈跟踪。例如:
When any exception occurs on the ASP.MVC server side code, I would like to take the entire stack trace of the exception and place in the ViewData and returns to the client. For example:
try
{
//some code
}
catch (SomeException e)
{
ViewData["exceptionStack"] = e.StackTrace;
}
在客户端JavaScript的将只是采取在ViewData的字符串,并显示它。例如:
The JavaScript on the client side would just take the string in the ViewData and display it. For example:
<script type="text/javascript">
var exceptionStack = '<%= ViewData["exceptionStack"] %>';
</script>
问题是我怎么能保证,可以通过正则表达式或其他手段,无论是在服务器端使用C#或客户端上的JavaScript变量的 exceptionStack 将不包含任何非法字符,从而使当我这样做:
The problem is how I can ensure, either via regex or other means, either on the server side using C# or on the client that the JavaScript variable exceptionStack would NOT contain any illegal character, so that when I do:
$('#someElement').text(exceptionStack);
或
$('#someElement').html(exceptionStack);
不会有任何错误。
there won't be any error.
推荐答案
我会说,使用HtmlEn code会工作。所以从控制器:
I would say that using HtmlEncode would work. So from the controller:
// Stuff in the controller action that may cause an error
catch(Exception ex)
{
ViewData["exceptionStack"] = Server.HtmlEncode(ex.ToString());
}
如果由于某种原因,HTML编码不为你工作,或者你想成为额外的安全,您还可以使用的 AntiXSS 库:
If for some reason Html Encoding doesn't work for you, or you want to be extra secure, you can also use the AntiXSS library:
// Stuff in the controller action that may cause an error
catch(Exception ex)
{
ViewData["exceptionStack"] = AntiXss.JavaScriptEncode(ex.ToString());
}
该HtmlEncoding可作为的HtmlHelper:
The HtmlEncoding is available as an HtmlHelper:
<%= Html.Encode(ViewData["exceptionStack"]) %>
和您可以轻松创建为AntiXSS库包装
And you can easily create wrappers for the AntiXSS libraries
public static string JavaScriptEncode(this HtmlHelper helper, string input)
{
return AntiXss.JavaScriptEncode(input);
}
然后可以以同样的方式被使用:
Which can then be used in the same way:
<%= Html.JavaScriptEncode(ViewData["exceptionStack"]) %>
当然AntiXSS还为HTML,XML,VBScript和URL编码的编码,所以你可以为任何或所有这些添加一个帮手。
Of course AntiXSS also has encoding for Html, XML, VBScript and Url encoding, so you could add a helper for any or all of those.
这篇关于在ASP.MVC,如何放在ViewData的异常的JavaScript友好的堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!