10.11. HTML Encoding

All web developers should be aware that it is important to HTML-encode values that are output to prevent XSS attacks (particularly if you have received them from the user). ASP.NET 4.0 offers a new markup syntax that uses the colon character to tell ASP.NET to HTML-encode the expression:

<%: "<script>alert('I won't be run'),</script>" %>

When ASP.NET parses this, it does the following:

<%= HttpUtility.HtmlEncode(YourVariableHere) %>

It is important to bear in mind that using this syntax may not negate all XSS attacks if you have complex nested HTML or JavaScript.

10.11.1. HtmlString

ASP.NET 4.0 includes the new HtmlString class that indicates an expression is already properly encoded and should not be reexamined. This prevents "safe" values from potentially firing dangerous request validation rules:

<%: new HtmlString("<script>alert('I will now be run'),</script>") %>

10.11.2. Custom Request Validation

It is now possible to override the default request validators by inheriting from the System.Web.Util.RequestValidator class and overriding the method IsValidRequestString(). You must then specify the custom validator in the httpRuntime section in Web.config:

<httpRuntime requestValidationType="Apress.MyValidator, Samples" />

10.11.3. Custom Encoders

If you think that ASP.NET's existing page encoders are insufficient, then you can now create your own by inheriting from the System.Web.Util.HttpEncoder class and specifying the new encoder in the encoderType attribute of httpRuntime, for example:

<httpRuntime encoderType="Apress.MyEncoder, Samples"  />

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.131.47