国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

ASP.NET mvc異常處理的方法示例介紹

2024-07-10 12:43: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();
}
}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 中超| 新巴尔虎左旗| 鹤庆县| 丹棱县| 辽阳县| 新民市| 江山市| 年辖:市辖区| 额济纳旗| 白水县| 岗巴县| 安宁市| 邵武市| 东乡族自治县| 平潭县| 仙桃市| 枣强县| 安阳市| 靖远县| 卢湾区| 从江县| 中西区| 香港| 通山县| 山东省| 田东县| 咸阳市| 拉孜县| 凤冈县| 汝阳县| 赣榆县| 米泉市| 沈丘县| 阿拉善左旗| 滨海县| 松桃| 龙胜| 甘肃省| 县级市| 石景山区| 司法|