用户名:
密 码: 记住
您当前的位置:首页 > 网络编程 > Net教程

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

时间:2015-01-29  来源:互联网  作者:佚名
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 使用js分页实现异步加载数据 asp.net 使用js分页实现异步加载数1、准备工作 引入“jquery-1.8.3.min.js”,AjaxPro.2.dll”
ASP.NET小结之MVC, MVP, MVVM比较以及区别(二) ASP.NET小结之MVC, MVP, MVVM比较以上一篇得到大家的关注,非常感谢。由于自己对于这些模式的理
相关文章
栏目更新
栏目热门