asp.net mvc - mvc 5 c#向数据库报告错误

本文关键字:mvc 数据库 报告 错误 net asp | 更新日期: 2023-09-27 18:02:27

我们有一个MVC应用程序,什么是最好的方式来记录错误产生(由用户)回到我们的支持数据库?用户应该只看到"this error has been reported"错误信息

所有的细节都应该写入到数据库

请帮忙!

asp.net mvc - mvc 5 c#向数据库报告错误

我建议你要么使用像Log4Net这样的外部库,要么创建你自己的库类,它将为你做日志记录。

另一个建议是利用在MVC文件中可用的ExceptionFilter,并编写登录该过滤器的代码。我建议,因为它不会让你一次又一次地编写代码,它遵循DRY原则。

示例:

public class CustomExceptionFilter: FilterAttribute,  
IExceptionFilter   
{  
    public void OnException(ExceptionContext filterContext)   
    {  
        if (!filterContext.ExceptionHandled)   
        {  
            //log error here 
            Logger.LogException(filterContext.Exception);
            //this will redirect to error page and show use logging is done 
            filterContext.Result = new   
                        RedirectResult("customErrorPage.html");  
             filterContext.ExceptionHandled = true;  
        }  
    }  
}

你可以这样做

//Over controller  
[CustomExceptionFilter]  
public class HomeController:Controller 
{  
   //......  
}  

//Over the Action  
[CustomExceptionFilter]  
public ActionResult Index() 
{  
   //.......  
}  

查看log4net教程