ASP.NET mvc异常处理 ASP.NET mvc异常处理的方法示例介绍

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

ASP.NET mvc异常处理 ASP.NET mvc异常处理的方法示例介绍

  2021-03-19 我要评论
想了解ASP.NET mvc异常处理的方法示例介绍的相关内容吗,在本文为您仔细讲解ASP.NET mvc异常处理的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:ASP.NET,mvc,异常处理,下面大家一起来学习吧。
1.首先常见保存异常的类(就是将异常信息写入到文件中去)
复制代码 代码如下:

public class LogManager
{
private string logFilePath = string.Empty;
public LogManager(string logFilePath)
{
this.logFilePath = logFilePath;
FileInfo file = new FileInfo(logFilePath);
if (!file.Exists)
{
file.Create().Close();
}
}
public void SaveLog(string message, DateTime writerTime)
{
string log = writerTime.ToString() + ":" + message;
StreamWriter sw = new StreamWriter(logFilePath, true);
sw.WriteLine(log);
sw.Close();
}
}

2、控制器异常处理

这种方式就在需要进行异常处理的controller中重写OnException()方法即可,因为它本身继承了IExceptionFilter接口
复制代码 代码如下:

public class ExceptionController : Controller
{
public ActionResult Index()
{
throw new Exception("我抛出异常了!");
}
protected override void OnException(ExceptionContext filterContext)
{
string filePath = Server.MapPath("~/Exception。txt");
StreamWriter sw = System.IO.File.AppendText(filePath);
sw.WriteLine(DateTime.Now.ToString() + ":" + filterContext.Exception.Message);
sw.Close();
base.OnException(filterContext);
Redirect("/");
}
}

3、过滤器异常处理
复制代码 代码如下:

namespace MyMVC.Controllers
{
public class ExceptionController : Controller
{
[Error]
public ActionResult Index()
{
throw new Exception("过滤器异常!");
}
}
}
public class ErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
string path = filterContext.HttpContext.Server.MapPath("~/Exception.txt");
StreamWriter sw = System.IO.File.AppendText(path);
sw.WriteLine(DateTime.Now.ToString()+":"+filterContext.Exception.Message);
sw.Close();
}
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们