I have a form that is used to create a memo, to do that I am using a rich text editor to provide some styling, this creates html tags in order to apply style. When I post that text, the mvc throws an error to prevent potentially dangerous scripts, so I have to specifically allow it.
I have found 2 ways of doing this, one is to decorate the controller method with [ValidateInput(false)]
and the other is to decorate the ViewModel
attribute with [AllowHtml]
. To me, [AllowHtml]
looks much nicer, but I have only found that approach used 1 time and the [ValidateInput(false)]
seems to be the preferred way.
Which method should I use and what are the differences between the two?
ValidateInput(false) attribute is used to allow sending HTML content or codes to server which by default is disabled by ASP.Net MVC to avoid XSS (Cross Site Scripting) attacks.
The ValidateInput attribute is used to allow sending the HTML content or codes to the server which, by default, is disabled by ASP.NET MVC to avoid XSS (Cross-Site Scripting) attacks. This attribute is used to enable or disable the request validation. By default, request validation is enabled in ASP.NET MVC.
ValidateInput and AllowHTML are directly connected with XSS security issues.
So let us first try to understand XSS.
XSS (cross-site scripting) is a security attack where the attacker injects malicious code while doing data entry. Now the good news is that XSS is by default prevented in MVC. So if any one tries to post JavaScript or HTML code he lands with the below error.
But in real time there are scenarios where HTML has to be allowed, like HTML editors. So for those kind of scenarios you can decorate your action with the below attribute.
[ValidateInput(false)] public ActionResult PostProduct(Product obj) { return View(obj); }
But wait, there is a problem here. The problem is we have allowed HTML on the complete action which can be dangerous. So if we can have more granular control on the field or property level that would really create a neat, tidy and professional solution.
That’s where AllowHTML is useful. You can see in the below code I have decorated “AllowHTML” on the product class property level.
public class Product { public string ProductName { get; set; } [AllowHtml] public string ProductDescription { get; set; } }
So summarizing “ValidateInput” allows scripts and HTML to be posted on action level while “AllowHTML” is on a more granular level.
I would recommend to use “AllowHTML” more until you are very sure that the whole action needs to be naked.
I would recommend you to read the blog post Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML which demonstrates step by step about the importance of these two attributes with an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With