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

所属分类: 网络编程 / ASP.NET 阅读数: 481
收藏 0 赞 0 分享
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();
}
}
更多精彩内容其他人还在看

asp.net下大文件上传知识整理

asp.net下大文件上传知识整理
收藏 0 赞 0 分享

Asp.Net常用函数

Asp.Net常用函数
收藏 0 赞 0 分享

asp.net下用url重写URLReWriter实现任意二级域名的方法第1/2页

asp.net下用url重写URLReWriter实现任意二级域名的方法
收藏 0 赞 0 分享

在.NET中利用XMLHTTP下载文件的代码

在.NET中利用XMLHTTP下载文件的代码
收藏 0 赞 0 分享

在ASP.NET 中实现单点登录

在ASP.NET 中实现单点登录
收藏 0 赞 0 分享

c# .net 生成图片验证码的代码

c# .net 生成图片验证码的代码
收藏 0 赞 0 分享

asp.net中MD5 16位和32位加密函数

asp.net中MD5 16位和32位加密函数
收藏 0 赞 0 分享

自己常用到的自定义公共类(已测试通过)

自己常用到的自定义公共类(已测试通过)
收藏 0 赞 0 分享

ASP.NET 2.0下随机读取Access记录的实现方法

ASP.NET 2.0下随机读取Access记录的实现方法
收藏 0 赞 0 分享

.NET(C#)连接各类数据库代码-集锦

.NET(C#)连接各类数据库代码-集锦
收藏 0 赞 0 分享
查看更多