How to avoid “Potential Dangerous Request.QueryString” in mvc

In some instances we might wan’t to allow html tags in our web application. But sad to say ASP.NET MVC blocks us from doing this. Chek out the below scenario. I want to add a comment and I want it italicized.

– Below is our form. When we submit this form it will result to?


– Yes you are right, to an error. After submitting the form this is the result. By default MVC blocks potentially malicious scripts.



– But what if we want to allow valid htm tags such as the italics tag? What do we do then? One of the best ways I found is to block inputs containing <script> tags and allow those that are non script tags . So how do we do that?

Let’s modify our ActionResult a little bit by adding [ValidateInput(false)] attribute in our action.

public ActionResult AddComment(string comment)
     if (System.Text.RegularExpressions.Regex.IsMatch(comment, “<script>.*?</script>”)) {
          throw new HttpException(500, “Potantially malicious Request.QueryString detected.”);
     else {
          ViewBag.Message = comment;
     return View(“Index”);

As you notice from the above snippet I am checking if the input contains tags. If it does, I displayed the message that the input is not valid, otherwise, I displayed what they have typed in the message box.

– Once we run our app again and tried to input html tags appart from <script> tags, it run’s smoothly as shown below. Else we throw our own exception. disallowing script tags that might cause serious problems in our app.


And that is it. You are now allowing safe html tags in your web app.

Happy coding.

By the way the entire source is in github.


Author: francorobles

A soon to be jedi in the art of software development...

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s