asp.net mvc razor html encoding

HTML Encoding

为了跨站点的脚本攻击,Razor 语法会直接将脚本代码编码输出。

@{
string message = "<script>alert('haacked!');</script>";
}
<span>@message</span>

输出:

<span>&lt;script&gt;alert(&#39;haacked!&#39;);&lt;/script&gt;</span>

此条实际测试时(chrome版本 37.0.2062.120 m,IE11)均显示为: <span><script>alert('haacked!');</script></span>

如果需要原样输出 代码文本 需要使用 @Html.Raw():

@{
string message = "<strong>This is bold!</strong>";
}
<span>@Html.Raw(message)</span>
输出:
<span><strong>This is bold!</strong></span>

实际测试: 显示为:This is bold!     当作html标记执行了!!!

如果 message ="<script>alert('haacked!');</script>"; 那么 

<span>@Html.Raw(message)</span>  会弹出一个 haacked!  对话框,执行js脚本!

posted @ 2014-11-11 15:36  李子康  阅读(290)  评论(0编辑  收藏  举报