Handle Cross-site scripting Error in ASP.NET

Our object is to prevent cross-site scripting and customize error message generated by cross-site exception in asp.net.

First Method:

In web.config set validateRequest = true for complete site.
<pages buffer="true" validateRequest="true" />

You can disable it for a particular page to set validateRequest="false" in page directive.
<%@ Page ValidateRequest=”false” %>


To enable it at page level instead of complete site
<%@ Page ValidateRequest=”true” %>
and set validateRequest="false" in web.config.

When script is injected then It will throw HttpRequestValidationException.

A potentially dangerous parameter value was detected from the client (txt="<script>alert('hello...").

We can handle or capture HttpRequestValidationException to show user friendly message.

Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error

‘If String.Compare(Server.GetLastError.GetType().ToString.Trim, "System.Web.HttpRequestValidationException", True) = 0 Then
If Server.GetLastError.GetType Is GetType(System.Web.HttpRequestValidationException) Then
Response.Write("You entered inappropriate characters.<br>")
Response.Write("Start Over or click Back.")
End If
End Sub

Second Method:
1. Disable request validation
2. Use the HttpUtility.HtmlEncode method to encode output
3. use HttpUtility.UrlEncode to encode output URLs
4. use validation controls or regular expression
I recommend second one.

1 comment:

  1. Handling the exception example you provided worked flawlessly...tried a lot of other suggestions but this one worked!!!