Content:
|
ASP.NET 1.1 has this nice "feature" of automatically validating the incoming Request (QueryString, Form and Cookies) to prevent script attacks. This new validation code will raise an HttpRequestValidationException, which will be raised before the OnInit itself is executed. The problem I have with that, is the fact that the resulting error message is not very nice. And although I could define an error page, I'd much rather give the user a friendly reminder that HTML is not allowed (in comments below, for example). Of course, I could turn the validation off, by specifying validateRequest="false" in the Page directive of my ASP.NET page, but I don't really want to do that...
It turned out that I only needed to make sure the Error event of my ASP.NET page was assigned before the validation is raising an exception. To do this, I had to declare a constructor, and set the Error event manually (since the assignment in the InitializeComponents would be too late).
In effect, I ended up with the following code:
constructor TWebForm1.Create; begin inherited; Include(Self.Error, Self.TWebForm1_Error) end;
And then in the Error handler we can clear the error and set the StatusCode back to 200, as follows:
procedure TWebForm1.TWebForm1_Error(sender: System.Object; e: System.EventArgs); begin if (Server.GetLastError.GetBaseException is System.Web.HttpRequestValidationException) then begin Response.Write('Sorry, no HTML allowed...'); Response.StatusCode := 200; Response.&End end end;
This still results in an error page (a bit nicer), and not my original page. So, I had to add a little trick to it, redirecting to the original page with an additional queryfield, so I can give a nice error message (and still show the original page).
procedure TWebForm1.TWebForm1_Error(sender: System.Object; e: System.EventArgs); begin if (Server.GetLastError.GetBaseException is System.Web.HttpRequestValidationException) then begin Response.StatusCode := 200; Response.Redirect(Request.Url.ToString + '?Ex=42', True) end end;
In the Page_Load, I can now check for the Request.Params['Ex'] to see if an error was raised, so I should give the user a friendly error message instead.
if Request.Params['Ex'] = '42' then lbError.Text := 'Sorry, no HTML allowed here!';
Go ahead and try to enter HTML in the comment box below. It shouldn't work, but at least I give you a friendly reminder ;-)
|