asp.net mvc razor html encoding

时间:2023-03-09 18:09:18
asp.net mvc razor html encoding

HTML Encoding

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

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

输出:

<span>&lt;script&gt;alert('haacked!');&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脚本!