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"

4

1 回答 1

2

编写一个检查文本框是否不包含 HTML 的验证器并不容易。这是因为 HTML 不是由某些字符定义的,而是由它们的组合定义的。包含<, '>' 甚至<script>不一定是 HTML 的文本。

您应该采用允许值的方法。如果一个文本框应该只包含数字,那么像这样验证它。

通过覆盖Application_ErrorGlobal.asax您可以捕获此异常并将用户重定向到更有意义的错误页面

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

如果你使用 Elmah,事情就更简单了。Elmah 旨在与 ASP.Net 错误处理一起使用。

您需要HandleErrorAttributeApp_Start\FilterConfig(或Global.asax)中删除默认全局,然后在您的Web.config

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

如果您遇到麻烦,请查看这篇文章,它很好地解释了一切
http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

于 2014-12-08T07:58:47.613 回答