4

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"

Simon
  • 7,991
  • 21
  • 83
  • 163

1 Answers1

2

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 in Global.asax you can catch this exception and redirect the user to a more meaningful error page

protected void Application_Error()
{
    Exception lastError = Server.GetLastError();
    if (lastError is HttpRequestValidationException)
    {
        //redirect to a static page and show proper error message
    }
}

If 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 from App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:

<customErrors mode="On" defaultRedirect="~/error/" />

In case you run into trouble please check this article, it explains everything very well
http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
  • The Application_Error() function is still not catching the error, and instead, the error.cshtml is displayed. – Simon Dec 08 '14 at 09:43
  • I have added a protected override void OnException(ExceptionContext filterContext) function to the controller, and this function catches the error. Is this how it should be done? – Simon Dec 08 '14 at 09:53
  • You should follow this link: http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx – Mihai Dinculescu Dec 08 '14 at 09:58