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

首頁 > 編程 > .NET > 正文

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

2024-07-10 13:27:32
字體:
來源:轉載
供稿:網友
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("http://m.survivalescaperooms.com/");
}
}


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();
}
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 综艺| 河间市| 崇阳县| 丰镇市| 重庆市| 沙雅县| 呼玛县| 西昌市| 佛坪县| 卓尼县| 合阳县| 临泉县| 利津县| 三门县| 繁峙县| 临夏市| 思茅市| 嘉义县| 九江县| 固镇县| 龙井市| 南岸区| 库尔勒市| 高雄县| 通州市| 木兰县| 平乐县| 得荣县| 菏泽市| 嘉峪关市| 敦化市| 沙河市| 陕西省| 监利县| 老河口市| 陆河县| 松阳县| 拜城县| 天长市| 古田县| 双鸭山市|