Thursday, August 27, 2009

ASP.NET MVC and ReverseDOS

I've blogged a bit about ReverseDOS before. It's a neat utility that allows you to lock up and/or deny HTML requests from content spammers. You know, you have a web site users are allowed to create content on, comments in particular, and the Online Consortium of Gambling Websites has targeted your site as a nice place to do some free advertising. ReverseDOS very easily allows you to tie up their resources and ignore their offerings.

The point of this post is that there is a trick to get ReverseDOS to show custom errors when using ASP.NET MVC. I forget where the original information came from to get this done. It's already out on the web somewhere, I just don't remember where I pulled the pieces from. Just in case it isn't easy to find, I'll show you how I got it done.

First, configure ReverseDOS just like the instructions tell you to. The one ReverseDOS configuration setting that you need to verify is that endRequest = false.

Next, in your Global.asax file, you need to add a new event handler.

protected void Application_PreRequestHandlerExecute()
var error = Context.Items["ReverseDOS_Exception"] as HttpException;
if (null != error)
ServeError("/Error/AccessDenied", 403);

Obviously, change the path to your own error page. The ServerError() method is an example of how to render a different ASP.NET MVC action to the response stream from outside of the MVC framework. This is basically the same as supplying a different view to render when returning from an action. The method looks something like this:

private void ServeError(string path, int statusCode)
var url = new StringBuilder();


string originalPath = Request.Path;
Context.RewritePath(url.ToString(), false);
IHttpHandler httpHandler = new MvcHttpHandler();
Context.RewritePath(originalPath, false);

Response.StatusCode = statusCode;

Granted, there are probably other ways of handling this. In my admittedly limited experience however, this gives me the most control when setting up ReverseDOS along side custom error handling in ASP.NET MVC. It allows me to serve my own error pages with proper http response codes without redirects and without relying on IIS features.

Happy coding to you.

No comments:

Post a Comment