I am developing an MVC5 internet application and have a question in regards to user input having HTML data.
I understand that if I want to have HTML code in a model, I can include the [AllowHtml]
data annotation and then sanitize the objects field.
My question is this, for any object field that does not have the [AllowHtml]
data annotation, where the user enters some HTML code, is it possible to cater to this error rather than have the Error.cshtml
display the error?
Ideally, I would like to display a validation message in the view before the Error.cshtml
displays and logs the error.
Is this possible? How can I cater to the error before the Error.cshtml
displays and logs the error.
Thanks in advance.
UPDATE
I have a function as follows in the Global.asax
file:
protected void Application_Error(object sender, EventArgs e)
This function catches my errors such as when the user goes to a page that does not exist, however, the http error
in question goes directly to the error.cshtml
file.
How can I edit my code so that the Application_Error
function catches this error?
I am using Elmah
for logging and have customErrors mode="On"
It's not that easy to write a validator that checks if a textbox doesn't contain HTML. This is because HTML is not defined by certain characters, but instead by a combination of them. A text containing
<
, '>' or even<script>
isn't necessarily HTML.You should take the approach of the allowed values. If a textbox should contain only number, then validate it like so.
By overriding
Application_Error
inGlobal.asax
you can catch this exception and redirect the user to a more meaningful error pageIf you're using Elmah things are even simpler. Elmah is designed to work with ASP.Net error handling.
You need to remove the default global
HandleErrorAttribute
fromApp_Start\FilterConfig
(orGlobal.asax
), and then set up an error page in yourWeb.config
:In case you run into trouble please check this article, it explains everything very well
http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx