ASP.Net未处理的异常处理程序来操纵响应

时间:2017-10-09 09:40:28

标签: c# asp.net

我正在开发一个ASP.net网站,当发生未处理的异常时,该网站需要在httpcontext中发回错误响应。我无法重定向到另一个页面,因为消费者只会出于登录目的而访问我的网站,除了响应之外不会看到任何页面。

我想过使用word = words[string.toLowerCase()]; ,但我的网站用完了.Net 3.5框架而无法使用它。

有人可以让我知道我能做些什么吗,我需要一个普通的httpmodule来捕获所有异常,然后发送一个带有错误信息的httpresponse,格式如下。

System.Web.Http.ExceptionHandler

1 个答案:

答案 0 :(得分:0)

我在Global.asax代码中执行以下操作(从VB转换)

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Server.ClearError();

    Logging.LogError(exception);
    //Get a HTML file stored in resources which contains my error text and some tokens to replace.
    dynamic html = My.Resources.ErrorText;
    html = html.Replace("{Title}", Server.HtmlEncode(My.Application.Info.Title));
    html = html.Replace("{Product}", Server.HtmlEncode(My.Application.Info.ProductName));
    html = html.Replace("{Version}", Server.HtmlEncode(My.Application.Info.Version.ToString));

    //Build my exception message looping though all the inner exceptions
    dynamic errorDetails = exception.Message + Constants.vbNewLine + exception.StackTrace;

    while (exception.InnerException != null) {
        exception = exception.InnerException;
        errorDetails += Constants.vbNewLine + Constants.vbNewLine + "Inner Exception: " + Constants.vbNewLine + exception.Message + Constants.vbNewLine + exception.StackTrace;
    }

    //Replace the {ErrorDetails} tag with my error text
    html = html.Replace("{ErrorDetails}", Server.HtmlEncode(errorDetails).Replace(Constants.vbNewLine, "<br/>"));

    //Replace the logo tag
    using (IO.MemoryStream ms = new IO.MemoryStream()) {
        using (img == My.Resources.Logo) {
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            dynamic logoBytes = ms.ToArray;
            html = html.Replace("{Logo}", "data:image/png;base64," + Convert.ToBase64String(logoBytes, 0, logoBytes.Length));
        }
    }

    //Replace the response
    Response.Clear();
    Response.Write(html);
    Response.Flush();
}

应该可以在httpsodule的init中为HttpApplication.Error事件添加事件处理程序来执行相同的操作。请参阅传递给Init方法https://msdn.microsoft.com/en-us/library/system.web.httpapplication_events(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.web.ihttpmodule(v=vs.110).aspx