Reputation: 582
In some part of my .cshtml
file, I should render Html
that users entered with Html-Editor
.
My code is :
<div id="description">
@Html.Raw(Model.Html)
<div>
but @Html.Raw()
is not safe from XSS Attacks
for example if user's entered Html content was something like this :
"<script>alert('XSS attack!')</script>"
this script run after entering this page!
how can I prevent from running these scripts(in general XSS attack) while rendering Html ?
Upvotes: 0
Views: 4334
Reputation: 14655
You can encode the HTML before rendering it:
@Html.Raw(Html.Encode(Model.Html))
But this is the same as rendering it using:
@Model.Html
If you render the HTML, use view source, or your browser's inspector, and copy the generated script
tag, you'll see it's been encoded:
<script>alert('XSS attack!')</script>
But I personally prefer using the combination of Html.Raw
and Html.Encode
because it makes it clearer to the reader what the intent is.
Upvotes: 2