- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
关于属性上的装饰器 [AllowHtml]
甚至是方法上的 [ValidateInput(false)]
,捕获 的最佳方法是什么HttpRequestValidationException
并将其附加到 ModelState 以在用户端显示为友好错误而不显示错误页面(在 Application_Error
下抛出新页面或使用自定义错误页面.
在 global.asax
中我有一个陷阱:
protected void Application_Error()
{
// http://romsteady.blogspot.dk/2007/06/how-to-catch-httprequestvalidationexcep.html
// Code that runs when an unhandled error occurs
System.Exception ex = Server.GetLastError();
if (ex is System.Web.HttpRequestValidationException)
{
// I got the exception here, I can do plenty now!
Server.ClearError(); // no need to continue, I know the error
}
}
如何在不使用任何 session /应用程序变量的情况下从此处进入模型状态(考虑此处的云以及所有托管用户请求的不同服务器)?
我在考虑添加到路线或 TempData
但这里不可用...也许是 Cookie
但接缝很黑...
Any ideas?
最佳答案
我曾经通过自定义 ModelBinder 并围绕 base.BindModel 调用抛出 try/catch 来处理这种情况。它很丑陋,但可以完成工作。
我再说一遍,它很丑。
这是一个例子:
public class FooModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Foo model;
try
{
model = (Foo)base.BindModel(controllerContext, bindingContext);
}
catch (HttpRequestValidationException)
{
// handle here
}
}
}
现在,在用错误填充 ModelState 的勇敢努力中,我有一个助手类,它会尽力维护状态。它的使用(和实现)还有很多不足之处(大量管道、魔术字符串的使用、类型特定、异常消息文本的正则表达式等),因此欢迎提出任何建议。这是最丑陋的部分,imo。
用法:
// from above code snippet
catch (HttpRequestValidationException)
{
// handle any potentially dangerous form values here. Don't want an exception bubbling up to the user
// so handle the HttpRequestValidationException by hand here
// manually populate the model here so that the original values are presented back to the user
model = new Foo()
{
Bar = HandleHttpRequestValidationExceptionHelper.TryAssignment(bindingContext.ModelState, () => bindingContext.ValueProvider.GetValue("Bar").AttemptedValue),
Baz = HandleHttpRequestValidationExceptionHelper.TryAssignment(bindingContext.ModelState, () => bindingContext.ValueProvider.GetValue("Baz").AttemptedValue)
};
}
return model;
助手尽最大努力为用户挖掘出相关的错误信息,但它确实很糟糕。 (注意到主题了吗?)
实现:
public static class HandleHttpRequestValidationExceptionHelper
{
/// <summary>
/// Use TryAssignment in anticipation of a HttpRequestValidationException; it's used to help return error information to the user
/// </summary>
/// <param name="modelStateDictionary">The ModelStateDictionary to add the errors to</param>
/// <param name="action">The attempted value to assign</param>
/// <returns>Either the proper value or the errored value read from the HttpRequestValidationException Message property</returns>
public static string TryAssignment(ModelStateDictionary modelStateDictionary, Func<string> action)
{
try
{
return action();
}
catch (HttpRequestValidationException ex)
{
// in effort to better inform the user, try to fish out the offending form field
var parenthesesMatch = Regex.Match(ex.Message, @"\(([^)]*)\)");
if (parenthesesMatch.Success)
{
var badFormInput = parenthesesMatch.Groups[1].Value.Split('=');
modelStateDictionary.AddModelError(badFormInput[0], badFormInput[1] + " is not valid.");
return badFormInput[1].TrimStart('"').TrimEnd('"');
}
else
{
// if attempt to find the offending field fails, just give a general error
modelStateDictionary.AddModelError("", "Please enter valid information.");
return string.Empty;
}
}
}
/// <summary>
/// Use TryAssignment in anticipation of a HttpRequestValidationException; it's used to help return error information to the user
/// </summary>
/// <typeparam name="T">Type of the value</typeparam>
/// <param name="modelStateDictionary">The ModelStateDictionary to add the errors to</param>
/// <param name="action">The attempted value to assign</param>
/// <returns>Either the proper value or default(T)</returns>
public static T TryAssignment<T>(ModelStateDictionary modelState, Func<T> action)
{
try
{
return action();
}
catch (HttpRequestValidationException ex)
{
// in effort to better inform the user, try to fish out the offending form field
var parenthesesMatch = Regex.Match(ex.Message, @"\(([^)]*)\)");
if (parenthesesMatch.Success)
{
var badFormInput = parenthesesMatch.Groups[1].Value.Split('=');
modelState.AddModelError(badFormInput[0], badFormInput[1] + " is not valid.");
// can't really cast a string to an unknown type T. safer to just return default(T)
}
else
{
// if attempt to find the offending field fails, just give a general error
modelState.AddModelError("", "Please enter valid information.");
}
return default(T);
}
}
}
基本上,在捕获异常时,尝试手动重新绑定(bind)模型,准备捕获每个属性的潜在 HttpRequestValidationException
错误。如果有人被捕获,请使用尽可能具体的消息相应地填充 ModelStateDictionary。
我真的希望该框架能够更轻松地 1) 捕获此异常和 2) 优雅地处理它,而不是把整个床都弄脏。
关于c# - 捕获 HttpRequestValidationException 并将其添加到 ModelState 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11224901/
我的 Controller 代码如下: [HttpPost] public ActionResult Create(ExampleViewModel model) { model.User.R
我正在开发 MVC5 代码优先应用程序。 在一个模型的 Edit() View 中,我包含了 [Create] 按钮,用于从 Edit() 中向其他模型添加新值> 查看并在 Edit() 上的 Dro
我的 MVC 应用程序中有一个问题,我不确定如何解决,或者我是否以错误的方式解决了这个问题。 我有一个 Controller / View ,它在带有复选框的网格中显示项目列表,当项目发布到我的 Co
我想知道是否可以自动将错误添加到 ModelState,以便检查我的 else 条件? if (ModelState.IsValid) { //Do something } else {
我有一个带有必需属性的模型对象 public class ApiPing { [Required] public DateTime ClientTime { get; set; }
如何测试 Controller.ViewData.ModelState?我宁愿在没有任何模拟框架的情况下这样做。 最佳答案 当然,如果您对数据使用存储库模式,则不必使用 Mock。 一些例子: htt
我正在使用 ASP.NET-MVC Core 2.1,我的代码中有这个 ViewModel 类 public class HomeViewModel { public
我有一个非常简单的 MVC 2 表单。它有两个下拉菜单,用户和角色。无论我选择什么,员工下拉列表都会通过验证,而角色下拉列表不会通过验证。尽管我计划实现一个,但没有默认的“空”选项,这就是为什么我需要
例如,有一个 Web Api 操作方法: public HttpMessageResponse Post(UserDto userDto) { if (!this.ModelState.IsV
如果我有以下模型: public class Model { public int ModelID { get; set; } public string Title { get; s
我的 DropDownLists 有一些问题,因为当我发布信息并且我的模型无效时,它返回“空”到页面触发错误,就像 this question . 我已经使用那里提出的解决方案,它解决了我的问题。无论
我的 DropDownLists 有一些问题,因为当我发布信息并且我的模型无效时,它返回“空”到页面触发错误,就像 this question . 我已经使用那里提出的解决方案,它解决了我的问题。无论
我想从 html 页面上的 dropdownList 获取参数并将其发送到我的 Controller ,创建新的模型对象,并将其插入数据库。 这是我的 Controller (创建 My_Model
我几乎总是想在回发时检查 ModelSate.IsValid 是否被调用。而且必须在每次回发开始时进行检查违反了 DRY 原则,有没有办法让它自动检查? 例子: [HttpPost("Register
我的模型类如下: public class PostInputViewModel { [Required] [MinLength(1)] [Ma
如何在 WEB Api .net 框架中将模型状态键设置为驼峰式大小写。 我使用 JsonProperty 特性将属性名称设置为驼峰式大小写。现在我希望 modelstate 与 json(驼峰式)相
所以,我有一个我很好奇的问题。我有一个 UserAccountViewModel,我正在重复使用它来创建帐户 View 和编辑帐户 View 。这样我就可以为我的代码使用一个 View 和一个 Vie
我正在编写一个 MVC 应用程序,其中包含一个对其进行验证的表单。 当我查询错误时,像这样: foreach (ModelState modelState in ViewData.ModelState
使用 MVC 时,当属性级别出现错误时,我们可以将错误添加到 ModelState但同样的错误也被添加到摘要中。我们如何避免显示它两次。 我只想在消息摘要中显示公共(public)错误,而在属性级别显
我有以下代码: public class EventController : ApiController { public IHttpActionResult Post(List Events
我是一名优秀的程序员,十分优秀!