如何使用 AddModelError 处理 HttpRequestValidationException 并返回有意义的错误?
我想处理HttpRequestValidationExceptions(例如,当将html插入表单字段时)并在提交后将用户返回到页面,并显示有意义的错误以突出显示问题。
例如,在登录页面上,如果用户在用户名字段中输入一些无效字符,那么我想捕获 HttpRequestValidationException 并将用户返回到突出显示用户名字段的登录页面。
我可以使用 OnException 方法捕获继承自 HandleErrorAttribute 的类中的错误。
有没有办法从这里(或任何其他方式)让 Controller *ModelState* 添加错误?
注意:我不想关闭验证或重定向到错误页面。
例如:
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is HttpRequestValidationException)
{
ModelStateDictionary ModelState = <...>
ModelState.AddModelError("Error", "Invalid chars");
filterContext.HttpContext.Response
filterContext.ExceptionHandled = true;
HttpContextBase HttpContext = filterContext.HttpContext;
HttpContext.Response.Redirect(HttpContext.Request.Path);
return;
}
}
提前感谢您为我提供的任何帮助!
I would like to handle HttpRequestValidationExceptions (e.g. when html is inserted into form fields) and return the user back to the page after submission with a meaningful error to highlight the problem.
For example, on a login page, if the user types some invalid characters into the username field, then I would like to catch the HttpRequestValidationException and return the user to the login page with the username field highlighted.
I can catch the error in a class inheriting from HandleErrorAttribute using the OnException method.
Is there a way from here (or any other way) that I can get the Controller *ModelState* to add the error?
Note: I do not want to turn validation off or redirect to an error page.
e.g.:
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is HttpRequestValidationException)
{
ModelStateDictionary ModelState = <...>
ModelState.AddModelError("Error", "Invalid chars");
filterContext.HttpContext.Response
filterContext.ExceptionHandled = true;
HttpContextBase HttpContext = filterContext.HttpContext;
HttpContext.Response.Redirect(HttpContext.Request.Path);
return;
}
}
Thanks in advance for any help you can give me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
[AllowHtml]
数据注释 和您自己的自定义 数据注释,其中包含您需要的验证规则。请参阅此答案作为一个很好的示例。您的模型的属性可能如下所示:
这看起来有点傻,但到目前为止它是我遇到的最干净的解决方案。
Instead of capturing and handling the
HttpRequestValidationException
, you could decorate your model's properties with the[AllowHtml]
data annotation and your own custom data annotation, which contains the validation rules you require. See this answer for a good example.Your model's properties may look like this:
Which looks a bit silly, but so far it's the cleanest solution I've encountered.