我试图找到一个在所有 Application_Error
事件处理程序之后立即触发的事件,以便我可以修改发送的响应(弄乱状态代码和“位置” header 并创建一个新的正文)使用自定义 HttpModule。
我已经尝试连接到 Application_EndRequest
(因为我读到这是唯一保证触发的处理程序)但是在请求处理中修改响应 header 和我得到一个 HttpException
:
Server cannot append header after HTTP headers have been sent.
最佳答案
我认为 ASP.Net 在 ApplicationError 之后启动了一个新的响应,只是针对不同的错误处理页面。尝试处理此响应。
更新 好的:这是操作方法!
我想确保我们都可以附加一个错误处理程序,并且我们可以优雅地处理页面中的事件,所以我们不能让最后一个服务器错误为空,我们还希望能够添加标题!
在 web.config 中,添加:
<customErrors redirectMode="ResponseRewrite" mode="On">
<error statusCode="500" redirect="~/ErrorHandler.aspx"/>
</customErrors>
或者您要捕获的具体错误。在 httpModules 下:
<add name="ErrorModule" type="TestErrorLifecycle.ErrorModule, TestErrorLifecycle"/>
记录错误的代码在这个模块中:
public class ErrorModule : IHttpModule
{
private volatile object locker = new object();
public void Init(HttpApplication context)
{
context.Error += context_Error;
}
void context_Error(object sender, EventArgs e)
{
var app = sender as HttpApplication;
lock (locker)
{
assertLogDirectory(app.Server);
using (var fs = File.AppendText(app.Server.MapPath("~/logs/errorlog.txt")))
{
var lastException = app.Server.GetLastError();
if (lastException == null) throw new ApplicationException("Not expected...");
fs.WriteLine(lastException.Message);
}
}
// we could also do a Request.Redirect() here...
}
private void assertLogDirectory(HttpServerUtility server)
{
var logdir = server.MapPath("~/logs/");
if (!Directory.Exists(logdir))
Directory.CreateDirectory(logdir);
}
public void Dispose()
{
}
}
我只是将它写入文件系统。您可以使用内核文件事务或独占锁或其他任何方式,但因为我知道我只会从这里写入此文件,所以我选择了一个简单的私有(private)信号量。
我在 Default.aspx.cs 中添加这个只是为了测试:
protected void Page_Load(object sender, EventArgs e)
{
throw new ApplicationException("wtf, something wrong??!");
}
创建的文件 ErrorHandler.aspx 中包含此内容(为简短起见省略了一些部分):
<body>
<h2>Error handler</h2>
<form id="form1" runat="server">
<p>Last error: <asp:Label ID="lblError" runat="server" /></p>
</form>
</body>
这是页面类:
public partial class ErrorHandler : Page
{
public ErrorHandler()
{
Load += ErrorHandler_Load;
}
private void ErrorHandler_Load(object sender, EventArgs e)
{
Response.AddHeader("X-TESTING", "Yes it works...");
lblError.Text = Server.GetLastError() == null ? "noo, why is it null?!?" : Server.GetLastError().Message;
}
}
最后,我在 ErrorHandler.aspx 中获得了这些响应 header :
Server: ASP.NET Development Server/9.0.0.0
Date: Mon, 23 Feb 2009 00:37:45 GMT
X-AspNet-Version: 2.0.50727
X-TESTING: Yes it works...
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 725
Connection: Close
200 OK
如果您尝试直接添加到 Response.Headers-collection,您需要以管道模式运行 IIS:http://forums.asp.net/p/1253457/2323117.aspx
希望对您有所帮助!干杯 亨里克
关于ASP.NET 发布 Application_Error 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/576113/