2017-10-09 121 views
0

我正在处理一个ASP.net网站,当发生未处理的异常时,需要发送httpcontext中的错误响应。我无法重定向到另一个页面,因为消费者只会出于登录目的而点击我的网站,并且看不到除响应之外的任何页面。ASP.Net未处理的异常处理程序来操纵响应

我想过使用System.Web.Http.ExceptionHandler,但我的网站用完了.Net 3.5框架,我无法使用它。

有人可以给我一个我能做什么的想法,我需要一个通用的httpmodule来捕获所有的异常,然后用以下格式发送一个带有错误消息的httpresponse。

​​

回答

0

i执行以下操作中的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(); 
} 

它应该是可能的一个事件处理程序在一个HTTP模块的初始化添加到HttpApplication.Error事件照着做。见https://msdn.microsoft.com/en-us/library/system.web.httpapplication_events(v=vs.110).aspx这是传递给Init方法https://msdn.microsoft.com/en-us/library/system.web.ihttpmodule(v=vs.110).aspx

+0

是否有可能在一个httpmodule中做到这一点,所以我可以保持它的可重用? – Ramki

+0

看起来应该可以将一个事件处理程序添加到httpmodule的init中的HttpApplication.Error事件中。请参阅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 – apc