So asp.net mvc by default will validate any Request parameters to make sure that they don’t contain any html tags or scripts which stops xss attacks. This is a good thing. The trouble is detecting this so that you can tell your user that they are doing something naughty. Asp.net mvc will throw a nasty HttpRequestValidationException and your user will end up with a YSOD or some useless error page. For my application I decided to make a FriendlyValidateInputAttribute which will detect this use case, and add an appropriate error to the ModelState so that in your controller all you need to do is check ModelState.IsValid and you should be good to go.
The way this works is pretty hacky. Calling ValidateInput() doesn’t actually validate anything. It just sets flags indicating that on the next usage of certain inputs that they should be validated. Thats why there is a bogus lookup which forces the request to be validated , which allows me to catch the exception. I use the exceptions error message to work out which form field is invalid. Note this code is very prototypish :P so test before use!!
using System.Web;
using System.Web.Mvc;
public class FriendlyValidateInputAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.Controller.ControllerContext.HttpContext.Request;
var controller = (Controller) filterContext.Controller;
controller.ValidateRequest = false;
request.ValidateInput();
try
{
var bogus = request["bogus"]; // this will trigger the exception
}
catch (HttpRequestValidationException xssException)
{
var start = xssException.Message.IndexOf("(") + 1;
var end = xssException.Message.IndexOf("=");
var formField = xssException.Message.Substring(start, end - start);
controller.ModelState.AddModelError(formField, xssException.Message);
}
}
}


