I want to restrict the user giving html tags as input.
so how can i handle it globally in web.config file for my Asp.Net MVC project.
I have used ValidateInput(false), but it completely allowing the html tags to save in db.

- 31
- 3
1 Answers
XSS validation is enabled in MVC by default. So you do not have to restrict input of HTML (it is already restricted), instead you allow HTML input only for certain Actions or ViewModel properties that you have marked.
Setting [ValidateInput(false)]
attribute on an Action will disable the validation on the whole Action.
Setting [AllowHtml]
attribute on a ViewModel property allows HTML input for this property only. This is the recommended way to enable HTML input.
To solve your problem, you should remove the [ValidateInput(false)]
from your Action.
Further reading: Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML.
Also make sure you have configured the correct requestValidationMode
in your web.config. requestValidationMode 4.5 vs 2.0.
To provide a custom error message if the input validation fails, register an IExceptionFilter
in the Global.asax who checks whether the thrown exception is a HttpRequestValidationException
.
public class HttpRequestValidationExceptionFilter : FilterAttribute, IExceptionFilter {
public const int MySpecialStatusCodeIndicatingValidationError = 1337;
public void OnException(ExceptionContext filterContext) {
if (!filterContext.ExceptionHandled && filterContext.Exception is HttpRequestValidationException) {
// redirect to error controller, which shows custom message
filterContext.Result = new HttpStatusCodeResult(MySpecialStatusCodeIndicatingValidationError);
filterContext.ExceptionHandled = true;
}
}
}
For a possible mechanism to handle errors with special status codes, see ASP.NET MVC 404 Error Handling. The idea is to recognize the MySpecialStatusCodeIndicatingValidationError
and redirect to the correct action in the custom HttpErrorController
.

- 9,357
- 1
- 26
- 36
-
Thanks for your info, but what my intention is to send an error message to the user whenever user enters html tags in the textbox, and i want this to be handled globally at one place, it may be either at web.config, or Global.asax – Sailendra Volety Jul 13 '18 at 10:21
-
Please see my edit on how to catch the exception thrown by the default request validation and provide a custom message. – Georg Patscheider Jul 13 '18 at 12:03
-
Thanks for info, i have one more dout, is there any way to clear validation providers(which we give in global.asax ModelValidatorProviders.Providers.Clear();), and add custom validation provider in web.config file – Sailendra Volety Jul 13 '18 at 13:25