How to Html.Encode in webforms
I ha开发者_如何学Gove an ASP.NET Web Forms application. There is a page with TextBoxes and users enter search terms into these which are used to query the database.
I know that I need to prevent JavaScript injection attacks. How do I do this?
In MVC I would use Html.Encode
. It doesn't seem to be recognized in Web Forms.
Thanks!
You can use HttpUtility.HtmlEncode
If you are on ASP.NET 4 or newer, you can use this syntax:
<%: Model.Username %>
Which will HTML-encode the expression. Scott Gu explains the benefit of this syntax:
We chose the <%: %> syntax so that it would be easy to quickly replace existing instances of <%= %> code blocks. It also enables you to easily search your code-base for <%= %> elements to find and verify any cases where you are not using HTML encoding within your application to ensure that you have the correct behavior.
On webforms you can call
HttpUtility.HtmlEncode(foo);
Be careful to not double encode.
You can use Server.HtmlEncode (which translates to HttpServerUtility.HtmlEncode
) , but Microsoft has a better web protection library called AntiXSS that you can download from CodePlex. It includes a utility that uses a white-list approach to HtmlEncoding
(much safer and better, and recommended by OWASP although they point to an older version). It also has tools that allow you to get safe HTML fragments, etc.
If you look at nothing else, however, take a look at the OWASP top 10. It sounds like you're just scratching the surface of web app security, and this is the best resource out there. Cross-Site Scripting attacks are just one of a whole slew of things you need to defend against.
It's also the one you will need to conform to if you have to deal with any sort of compliance (PCI, Red flag, etc)
In .NET v4.0 and above, you can use the following on Web Forms:
<%
string notificationIcon = "<i class='fa fa-plus fa-icon fa-stack-right-top'></i>";
%>
<%: new HtmlString(notificationIcon) %>
Microsoft Docs
精彩评论