开发者

In ASP.MVC, how to place JavaScript-friendly Stack trace of exceptions in 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;
}

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>

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);

or

$('#someElement').html(exceptionStack);

there won't be any error.


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());
}

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());
}

The HtmlEncoding is available as an HtmlHelper:

<%= Html.Encode(ViewData["exceptionStack"]) %>

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"]) %>

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.


The method you are looking for is HtmlHelper.Encode:

<script type="text/javascript">
    var exceptionStack = '<%= Html.Encode(ViewData["exceptionStack"] %>)';
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜