C# 如何避免 ASP.NET MVC 中的 HttpRequestValidationException 呈现导致异常的相同视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/249066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:51:25  来源:igfitidea点击:

How to avoid HttpRequestValidationException in ASP.NET MVC rendering the same view which caused the exception

c#.netasp.netasp.net-mvcvb.net

提问by eKek0

I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs <BR/>, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted.

我只想知道如何在 ASP.NET MVC 中验证(或清除)用户输入,以便无论提交的值如何都不会抛出 HttpRequestValidationException。例如,对于文本输入,如果用户输入<BR/>,则会引发异常并显示黄屏死机。我不想要那个。我想捕获异常并使当前视图中的用户友好错误可见,最好使用加载了相同值的控件提交。

I have found this http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html, but it is useless for my purpose. Also, I have found this http://msdn.microsoft.com/en-us/library/aa973813.aspxand tried to put inside a model binder but I couldn't make to work.

我找到了这个http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html,但它对我的目的没用。另外,我找到了这个http://msdn.microsoft.com/en-us/library/aa973813.aspx并试图放入模型活页夹,但我无法工作。

采纳答案by user66787

With the latest version of ASP.NET MVC (the RC, at the time of writing this) you can just put an attribute on either your controller class or your action method, e.g.:

使用最新版本的 ASP.NET MVC(在撰写本文时为 RC),您只需在控制器类或操作方法上放置一个属性,例如:

[ValidateInput(false)]
public ActionResult create()
{
    // ...method body
}

The ValidateInputAttribute is in System.Web.Mvc.

ValidateInputAttribute 位于 System.Web.Mvc 中。

But as others have said, you do then have to perform your own manual input validation or cleaning.

但正如其他人所说,您必须执行自己的手动输入验证或清理。

Using MVC 3, you must also ensure this is in your Web.config: <system.web><httpRuntime requestValidationMode="2.0" /></system.web>

使用 MVC 3,您还必须确保它在您的 Web.config 中: <system.web><httpRuntime requestValidationMode="2.0" /></system.web>

回答by Hrvoje Hudo

Put put ValidateRequest="false" to your aspx view declaration, but sanitize users input text inside your code, to avoid some xss attacks.

将 put ValidateRequest="false" 放入您的 aspx 视图声明中,但在您的代码中清理用户输入的文本,以避免一些 xss 攻击。

回答by tvanfosson

Instead of catching the error in the global.asax Application_Error, you could catch it by adding an error handler for the controller that explicitly catches this error and redirects to the view with an error message and appropriate view data.

不是在 global.asax Application_Error 中捕获错误,您可以通过为控制器添加一个错误处理程序来捕获它,该控制器显式捕获此错误并重定向到带有错误消息和适当视图数据的视图。

I found this, somewhat old, poston how to do this with attributes.

我发现这个有点旧,关于如何使用属性执行此操作的帖子

回答by dariol

ValidateInputAttribute is the proper method for disabling request validation. Declarative method within view (aspx) doesn't work because controller is responsible for receiving request (not view/aspx).

ValidateInputAttribute 是禁用请求验证的正确方法。视图 (aspx) 中的声明性方法不起作用,因为控制器负责接收请求(而不是视图/aspx)。

回答by JoshNaro

For a very detailed example of how to catch this (and other) exceptions with a filter see: http://code.google.com/p/geochat/source/browse/Source/Web/GeoChat.MvcExtensions/ExceptionHandlerAttribute.cs

有关如何使用过滤器捕获此(和其他)异常的非常详细的示例,请参阅:http: //code.google.com/p/geochat/source/browse/Source/Web/GeoChat.MvcExtensions/ExceptionHandlerAttribute.cs

This will allow you to keep the validation on, but prevent the user from seeing the "yellow screen of death".

这将允许您保持验证,但防止用户看到“死亡黄屏”。

This is a simplified (perhaps oversimplified) version:

这是一个简化(可能过于简化)的版本:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class ExceptionHandlerAttribute : FilterAttribute, IExceptionFilter {

private HandleErrorAttribute attribute = new HandleErrorAttribute();

public ExceptionHandlerAttribute() {
  this.ExceptionType = typeof(Exception);
  this.Order = 1;
}

public string View {
  get {
    return attribute.View;
  }
  set {
    attribute.View = value;
  }
}

public Type ExceptionType {
  get {
    return attribute.ExceptionType;
  }
  set {
    attribute.ExceptionType = value;
  }
}

public void OnException(ExceptionContext filterContext) {
  if (this.ExceptionType.IsInstanceOfType(filterContext.Exception)) {
    string controller = (string)filterContext.RouteData.Values["controller"];
    string action = (string)filterContext.RouteData.Values["action"];
    if (controller == null)
      controller = String.Empty;

    if (action == null)
      action = String.Empty;

    HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controller, action);
    ViewResult result = new ViewResult();
    result.ViewName = this.View;
    result.MasterName = String.Empty;
    result.ViewData = new ViewDataDictionary<HandleErrorInfo>(model);

    result.TempData = filterContext.Controller.TempData;
    filterContext.Result = result;

    filterContext.ExceptionHandled = true;
    filterContext.HttpContext.Response.Clear();
    filterContext.HttpContext.Response.StatusCode = 500;
  }
}

}

}

回答by Kevin Southworth

In ASP MVC 3 you can use the [AllowHtml]attribute on individual fields/properties in your Model/ViewModel to turn off validation for just that field, which is pretty nice. I will add this attribute to certain fields in my model, and then use the excellent AntiXSSlibrary (also available via NuGet) to sanitize the user input by calling the Sanitizer.GetSafeHtmlFragment(mymodel.Description)(where the "Description" property is a string property on my view model, that has the [AllowHtml]attribute applied)

在 ASP MVC 3 中,您可以使用[AllowHtml]Model/ViewModel 中各个字段/属性的属性来关闭仅对该字段的验证,这非常好。我会将此属性添加到我的模型中的某些字段,然后使用优秀的AntiXSS库(也可通过 NuGet 获得)通过调用Sanitizer.GetSafeHtmlFragment(mymodel.Description)(其中“描述”属性是我的视图模型上的字符串属性,即是否[AllowHtml]应用了属性)