One of the greatest time-savers in web development is the use of dynamic pages to serve up database driven content. The most common examples of which are content management systems and product information pages. More times than not these pages hinge on a querystring parameter such as /page.aspx?id=12345 to determine which record needs to be retrieved from the database and output to the page. What is surprising is how many sites don't adequatly validate that crucial parameter.
Any parameter that can be tampered with by a user, such as a querystring, must be validated as a matter of basic security. That being said, this validation must also adequately deal with a situation when that parameter is not valid. Whether the parameter is for a non-existant record, or whether the parameter contains letters where it should only be numbers, the end-result is the same: the expected page does not exist. As simple as this sounds there are countless applications out there that seem to completely ignore any sort of error handling, and are content to have Server Error in "/" Application be the extent of their error handling. Somewhere in the development cycle the developers of these application decided that the default ASP.NET error page would be the best thing to show to the site's visitors, and that a 500 SERVER ERROR was the ideal response to send to any search engine spiders that might have the misfortune of coming across a link with a bad parameter in it.
With a dynamic page that depends on querystring parameters to generate its content, the following basic measures should be taken:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'Ensure that the requested URI actually has any querystring keys
If Request.Querystring.HasKeys() Then
'Ensure that the requested URI has the expected parameter, and that the parameter isn't empty
If Request.Querystring("id") IsNot Nothing Then
'Perform any additional type validation to ensure that the string value can be cast to the required type.
Response.StatusCode = 404
Response.StatusCode = 404
This is a basic example, but demonstrates how to perform simple validation against the querystring that will properly redirect anyone that reaches the page with a bad querystring in the request URL. A similar approach should be taken when attempting to retrieve the data in the case that the record is not found.
Another useful trick is to define the default error redirect in the web.config file (<customErrors mode="RemoteOnly" defaultRedirect="/error.aspx">), and use that page to respond to the error appropriately by using the Server.GetLastError() method to get the most recent server exception and handling that exception as required.
There are many other ways to manage server responses when there is an error in your ASP.NET application. What is most important is knowing that you need to handle these errors properly, up to and including an appropriate response to the request.