gpt4 book ai didi

c# - 使用NLog获取Application_Start()中的错误并重定向到友好页面错误

转载 作者:行者123 更新时间:2023-12-03 08:00:11 34 4
gpt4 key购买 nike

我需要在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.

最佳答案

在Global.Asax

    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();
}
}
将您各自的 View 添加到相同的 View
希望对您有帮助。谢谢你,祝你有美好的一天。

关于c# - 使用NLog获取Application_Start()中的错误并重定向到友好页面错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23130863/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com