使用NLog获取Application_Start()中的错误,并重定向到友好页面错误
本文关键字:错误 重定向 Application 获取 NLog Start 使用 | 更新日期: 2023-09-27 17:58:55
我需要捕捉Application_Start()中的任何错误并重定向到HTML错误页面,但如果我有错误,NLog不会记录任何内容,例如,数据库不可用:
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.
在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();
}
}
将您各自的视图添加到同一
希望它能帮助你。谢谢你,祝你今天愉快。