C# 如何在生产中捕获HttpRequestValidationException
我有这段代码来处理global.asax.cs文件中的HttpRequestValidationExceptionC# 如何在生产中捕获HttpRequestValidationException,c#,asp.net,asp.net-3.5,iis-7.5,global-asax,C#,Asp.net,Asp.net 3.5,Iis 7.5,Global Asax,我有这段代码来处理global.asax.cs文件中的HttpRequestValidationException protected void Application_Error(object sender, EventArgs e) { var context = HttpContext.Current; var exception = context.Server.GetLastError(); if (exception is HttpRequestValidat
protected void Application_Error(object sender, EventArgs e)
{
var context = HttpContext.Current;
var exception = context.Server.GetLastError();
if (exception is HttpRequestValidationException)
{
Response.Clear();
Response.StatusCode = 200;
Response.Write(@"<html><head></head><body>hello</body></html>");
Response.End();
return;
}
}
受保护的无效应用程序\u错误(对象发送方,事件参数e)
{
var context=HttpContext.Current;
var exception=context.Server.GetLastError();
if(异常为HttpRequestValidationException)
{
Response.Clear();
Response.StatusCode=200;
回答。写(@“你好”);
Response.End();
返回;
}
}
如果我调试我的Web应用程序,它工作得很好。但是,当我将它放在生产服务器上时,服务器会忽略它,并生成“从客户端检测到潜在危险的request.form值”错误页面。
我不知道到底发生了什么。。。
如果有人知道问题是什么,或者我做错了什么
另外,我不想在web.config中将validaterequest设置为false
服务器使用IIS7.5,我使用asp.NET3.5
谢谢,
布鲁诺好的,我自己找到的。
我必须纠正我最后的错误
protected void Application_Error(object sender, EventArgs e)
{
var context = HttpContext.Current;
var exception = context.Server.GetLastError();
if (exception is HttpRequestValidationException)
{
context.Server.ClearError(); // Here is the new line.
Response.Clear();
Response.StatusCode = 200;
Response.Write(@"<html><head></head><body>hello</body></html>");
Response.End();
return;
}
}
受保护的无效应用程序\u错误(对象发送方,事件参数e)
{
var context=HttpContext.Current;
var exception=context.Server.GetLastError();
if(异常为HttpRequestValidationException)
{
context.Server.ClearError();//这是新行。
Response.Clear();
Response.StatusCode=200;
回答。写(@“你好”);
Response.End();
返回;
}
}
另一种仅适用于MVC的方法是使用自定义异常过滤器:
- 创建实现IEExceptionFilter的自定义FilterAttribute
- 从FilterAttribute内部,可以重定向到用于显示错误的控制器或视图
- 在Global.asax或控制器的属性中注册过滤器
public class HttpRequestValidationExceptionAttribute : FilterAttribute, IExceptionFilter {
public void OnException(ExceptionContext filterContext) {
if (!filterContext.ExceptionHandled && filterContext.Exception is HttpRequestValidationException) {
filterContext.Result = new RedirectResult("~/HttpError/HttpRequestValidationError");
filterContext.ExceptionHandled = true;
}
}
}
我认为您不需要“context”变量。它与“Server.GetLastError()”和“Server.ClearError()”一样工作正常。Response.End()根据设计抛出异常。而是使用以下命令:
HttpContext.Current.ApplicationInstance.CompleteRequest
。请看下面的解释:使用@WildJoe和Kamran的注释(很抱歉不能同时通知这两个,谢谢),这看起来是一种非常可行和有用的方法来覆盖Web API中的默认错误处理+1.谢谢分享:-)我有空的时候会看的:-)谢谢。我使用了它,但发现filterContext.ExceptionHandled已设置为true,因此if语句中的代码未运行,并且显示了我的默认错误页面。我去掉了那个条件,现在看来它工作得很好。但不确定这样做是否会在其他地方引起问题。。。有什么想法吗?谢谢对ExceptionHandled的测试已完成,因此单个异常不会由多个筛选器处理。。有关进一步讨论,请参阅。此答案应被接受。在全局数据库中,使用筛选器比筛选所有异常要好