时间:2021-07-01 10:21:17 帮助过:20人阅读
- <br>public class LogManager <br>{ <br>private string logFilePath = string.Empty; <br>public LogManager(string logFilePath) <br>{ <br>this.logFilePath = logFilePath; <br>FileInfo file = new FileInfo(logFilePath); <br>if (!file.Exists) <br>{ <br>file.Create().Close(); <br>} <br>} <br>public void SaveLog(string message, DateTime writerTime) <br>{ <br>string log = writerTime.ToString() + ":" + message; <br>StreamWriter sw = new StreamWriter(logFilePath, true); <br>sw.WriteLine(log); <br>sw.Close(); <br>} <br>} <br> <br>2、控制器异常处理 <br><br>这种方式就在需要进行异常处理的controller中重写OnException()方法即可,因为它本身继承了IExceptionFilter接口 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>public class ExceptionController : Controller <br>{ <br>public ActionResult Index() <br>{ <br>throw new Exception("我抛出异常了!"); <br>} <br>protected override void OnException(ExceptionContext filterContext) <br>{ <br>string filePath = Server.MapPath("~/Exception。txt"); <br>StreamWriter sw = System.IO.File.AppendText(filePath); <br>sw.WriteLine(DateTime.Now.ToString() + ":" + filterContext.Exception.Message); <br>sw.Close(); <br>base.OnException(filterContext); <br>Redirect("/"); <br>} <br>} <br> <br>3、过滤器异常处理 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>namespace MyMVC.Controllers <br>{ <br>public class ExceptionController : Controller <br>{ <br>[Error] <br>public ActionResult Index() <br>{ <br>throw new Exception("过滤器异常!"); <br>} <br>} <br>} <br>public class ErrorAttribute : HandleErrorAttribute <br>{ <br>public override void OnException(ExceptionContext filterContext) <br>{ <br>base.OnException(filterContext); <br>string path = filterContext.HttpContext.Server.MapPath("~/Exception.txt"); <br>StreamWriter sw = System.IO.File.AppendText(path); <br>sw.WriteLine(DateTime.Now.ToString()+":"+filterContext.Exception.Message); <br>sw.Close(); <br>} <br>} <br></li><li> </li><li> </li></ol></pre></li></ol></pre>