2013-03-31 68 views
2

我正在爲我的MVC 4應用程序在THIS之後實現一個錯誤處理程序。
現在我對所有錯誤都做了相同的處理,不僅404,我想獲得原始響應以保存日誌或在調試模式下顯示它,因爲它包含有用信息,如完整的堆棧跟蹤,小型顯示代碼中發生錯誤的地方等等。在MVC中獲取響應內容

在調用Response.Clear()之前,我正在努力從Response對象中獲取緩衝repsonse數據,但無法弄清楚。

如何獲取HttpResonse對象的內容?

對於HttpWebResponse有一個GetResponseStream()方法,它可用於的是,在那裏我發現了很多的例子,但沒有爲HttpResonseOutputStream不能被讀取...

回答

1

不知道這可能會幫助到正確的方向,但我只是用這個:

[AttributeUsage(AttributeTargets.Class)] 
public class ErrorHandlerAttribute : FilterAttribute, IExceptionFilter 
{ 

    readonly BaseController _bs = new BaseController(); 

    public virtual void OnException(ExceptionContext fc) 
    { 
     var model = new errors 
     { 
      stacktrace = fc.Exception.StackTrace, 
      url = fc.HttpContext.Request.RawUrl, 
      controller = fc.RouteData.GetRequiredString("controller"), 
      source = fc.Exception.Source, 
      errordate = DateTime.Now, 
      message = fc.Exception.Message//, 
      //InnExc = String.IsNullOrEmpty(fc.Exception.InnerException.ToString()) ? fc.Exception.InnerException.ToString() : "" 
     }; 

     var message = "<html><head></head><body><h2>An error occured on " + _bs.GetKeyValue<string>("Mobile Chat App") + ".</h2>"; 
     message += "<strong>Message:</strong> <pre style=\"background-color:#FFFFEF\"> " + model.message + "</pre><br />"; 
     message += "<strong>Source:</strong> <pre style=\"background-color:#FFFFEF\">" + model.source + "</pre><br />"; 
     message += "<strong>Stacktrace:</strong><pre style=\"background-color:#FFFFEF\"> " + model.stacktrace + "</pre><br />"; 
     message += "<strong>Raw URL:</strong> <pre style=\"background-color:#FFFFEF\">" + model.url + "</pre></br />"; 
     message += "<strong>Inner Exception:</strong> <pre style=\"background-color:#FFFFEF\">" + model.InnExc + "</pre></br />"; 
     message += "<strong>Any Form values</strong>: <pre>" + fc.HttpContext.Request.Form + "</pre><br />"; 
     message += "</body></html>"; 

     fc.ExceptionHandled = true; 
     fc.HttpContext.Response.Clear(); 
     fc.HttpContext.Response.StatusCode = 500; 
     fc.HttpContext.Response.TrySkipIisCustomErrors = true; 

     _bs.SendErrorMail(message); 

     fc.ExceptionHandled = true; 
     //var res = new ViewResult { ViewName = "error" }; 
     //fc.Result = res; 
     fc.HttpContext.Response.Redirect("/ErrorPage"); 
     //fc.HttpContext.Response.RedirectToRoute("error",new{controller="Home",action="ErrorPage"}); 
    } 

我有一個Gmail的錯誤帳戶,我把所有的錯誤之中,並讓我知道如果有什麼毛病任何網站,我做,這有沒有失敗我的信息。我沒有看過這個以極大的程度上,因爲我用不同的方法,但這些天:

fc.HttpContext.Request.RawUrl, 

只是HttpContext的,你有沒有的HttpContext的保持,我使用URL get和fc.HttpContext .Request.Form獲取可能導致錯誤的任何和所有表單數據。

這不是你問的答案,但這是因爲我在請求期間發現了錯誤,而不是響應中的錯誤!然後清除響應(將出現錯誤500)並將其替換爲我的頁面上的重定向,該頁面上有一個帶鍵盤的猴子的漂亮圖片:-)

+0

該例外不包括默認錯誤準備的所有內容你,但現在我走了這條路。如果沒有人會很快給出更好的答案,我會接受你的... – ChrFin

+0

是的,我知道,但上面我用來基本上給我YSOD,我的電子郵件,這可能足以至少調試你的代碼/解決方案,沒有太多需要對於其他任何事情,我也將它與try/catch一起使用,並將異常發送給一個電子郵件編譯器,這樣我就不會錯過任何一個技巧,我學到的一個很好的技巧是包含瀏覽器類型,這幫助我發現了一個錯誤只針對黑莓瀏覽器 – davethecoder