2014-04-17 20 views
1

我需要捕獲Application_Start()中的任何錯誤並重定向到HTML錯誤頁面,但例如如果出現錯誤,NLog不記錄任何內容,數據庫不可用:使用NLog獲取Application_Start()中的錯誤並重定向到友好的頁面錯誤

private static Logger logger = LogManager.GetCurrentClassLogger(); 

protected void Application_Start() 
{ 
    try 
    { 
     AreaRegistration.RegisterAllAreas(); 
     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
     AutofacConfig.RegisterDependencies(); 
     AutoMapperConfiguration.Configure(); 
     AuthConfig.RegisterAuth(); 
     SimpleMemberShipConfig.SimpleMembershipInitializer(); 
     EntityFrameworkConfig.Configure(); 
    } 
    catch (Exception e) 
    { 
     logger.Error(e); 
    } 
} 

NLOG配置:

<targets> 

    <target xsi:type="File" name="Heelp_log" fileName="${basedir}/logs/Heelp-${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${callsite:className=true:includeSourcePath=true:methodName=true} ${message}" /> 

</targets> 
<rules> 

    <logger name="*" minlevel="Error" writeTo="Heelp_log" /> 

</rules> 

要重定向我:

<customErrors mode="On" defaultRedirect="~/Views/Shared/Error.html" /> 

但它關係到這樣一個頁面(/Views/Shared/Error.html?aspxerrorpath=/):

Server Error in '/' Application. 

Runtime Error 

Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated. 

回答

0

添加的方法在Gloabal.Ascx

protected void Application_Error() 
    { 
     var exception = Server.GetLastError(); 
     var httpException = exception as HttpException; 
     Response.Clear(); 
     Server.ClearError(); 
     var routeData = new RouteData(); 
     routeData.Values["controller"] = "Error"; 
     routeData.Values["action"] = "General";    
     routeData.Values["exception"] = exception; 
     Response.StatusCode = 500; 
     if (httpException != null) 
     { 
      Response.StatusCode = httpException.GetHttpCode(); 
      switch (Response.StatusCode) 
      { 
       case 403: 
        routeData.Values["action"] = "Http403"; 
        break; 
       case 404: 
        routeData.Values["action"] = "Http404"; 
        break; 
      } 
     } 

     IController errorsController = new ErrorController(); 
     var rc = new RequestContext(new HttpContextWrapper(Context), routeData); 
     errorsController.Execute(rc); 
    } 

,並添加ErrorController

public class ErrorController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult General() 
    {    
     return RedirectToAction("Index", "Error"); 
    } 

    public ActionResult Http404() 
    { 
     return View(); 
    } 

    public ActionResult Http403() 
    { 
     return View(); 
    } 
} 

加入你們各自的意見相同

希望它可以幫助你。謝謝你,祝你有美好的一天。

+0

嗨,謝謝!你如何建議我使用NLog記錄錯誤? – Patrick

相關問題