构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(12)-系统日志和异常的处理②...
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(12)-系统日志和异常的处理②
上一讲我们做了日志与异常的结果显示列表,这一节我们讲要把他应用系统中来。
首先我们在App.Common类库中创建一个通用类ResultHelper,这个类里面写了,获取一个GUID,获取当前时间,处理字符串等操作,虽然我们目前要用到的一个就是获取GUID但是以后我们可能还要用到别的,所以我都把他放进入了
然后在App.Admin创建一个核心文件夹,Core,放入LogHandler这个类是主要是写入日志,避免在每次都要实例化这个类,我把他封装起来,大家一看就知道。
然后修改Controller的Create方法,代码如下一一给出。
usingSystem;usingSystem.Web;usingSystem.Text.RegularExpressions;namespaceApp.Common {public classResultHelper{/// <summary>///创建一个全球唯一的32位ID/// </summary>/// <returns>ID串</returns>public static stringNewId{get{string id = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");string guid = Guid.NewGuid().ToString().Replace("-", "");id+= guid.Substring(0, 10);returnid;}}public static stringNewTimeId{get{string id = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");returnid;}}/// <summary>///截取字符串/// </summary>/// <param name="value">字符串</param>/// <param name="length">剩下长度</param>/// <returns>指定字符串并加...</returns>public static string SubValue(string value, intlength){if (value.Length >length){value= value.Substring(0, length); value = value + "..."; returnNoHtml(value);}else { returnNoHtml(value); }}//还原的时候public static string InputText(stringinputString){if ((inputString != null) && (inputString !=String.Empty)){inputString=inputString.Trim();//if (inputString.Length > maxLength)//inputString = inputString.Substring(0, maxLength);inputString = inputString.Replace("<br>", "\n");inputString= inputString.Replace("&", "&");inputString= inputString.Replace("'", "''");inputString= inputString.Replace("<", "<");inputString= inputString.Replace(">", ">");inputString= inputString.Replace("chr(60)", "<");inputString= inputString.Replace("chr(37)", ">");inputString= inputString.Replace("\"", """);inputString= inputString.Replace(";", ";");returninputString;}else{return "";}}//添加的时候public static string OutputText(stringoutputString){if ((outputString != null) && (outputString !=String.Empty)){outputString=outputString.Trim();outputString= outputString.Replace("&", "&");outputString= outputString.Replace("''", "'");outputString= outputString.Replace("<", "<");outputString= outputString.Replace(">", ">");outputString= outputString.Replace("<", "chr(60)");outputString= outputString.Replace(">", "chr(37)");outputString= outputString.Replace(""", "\"");outputString= outputString.Replace(";", ";");outputString= outputString.Replace("\n", "<br>");returnoutputString;}else{return "";}}/// <summary>///去除HTML标记/// </summary>/// <param name="NoHTML">包括HTML的源码</param>/// <returns>已经去除后的文字</returns>public static string NoHtml(stringHtmlstring){//删除脚本Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);//删除HTMLHtmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"…", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"—", "", RegexOptions.IgnoreCase);Htmlstring= Regex.Replace(Htmlstring, @"“", "", RegexOptions.IgnoreCase);Htmlstring.Replace("<", "");Htmlstring= Regex.Replace(Htmlstring, @"”", "", RegexOptions.IgnoreCase);Htmlstring.Replace(">", "");Htmlstring.Replace("\r\n", "");Htmlstring=HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();returnHtmlstring;}/// <summary>///格式化文本(防止SQL注入)/// </summary>/// <param name="str"></param>/// <returns></returns>public static string Formatstr(stringhtml){System.Text.RegularExpressions.Regex regex1= new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex2= new System.Text.RegularExpressions.Regex(@"href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex3= new System.Text.RegularExpressions.Regex(@"on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex4= new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex5= new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex10= new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex11= new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);System.Text.RegularExpressions.Regex regex12= new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);html= regex1.Replace(html, ""); //过滤<script></script>标记html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性html = regex3.Replace(html, "_disibledevent="); //过滤其它控件的on...事件html = regex4.Replace(html, ""); //过滤iframehtml = regex10.Replace(html, "s_elect");html= regex11.Replace(html, "u_pudate");html= regex12.Replace(html, "d_elete");html= html.Replace("'", "’");html= html.Replace(" ", " ");returnhtml;}/// <summary>///检查SQL语句合法性/// </summary>/// <param name="sql"></param>/// <returns></returns>public static bool ValidateSQL(string sql, ref stringmsg){if (sql.ToLower().IndexOf("delete") > 0){msg= "查询参数中含有非法语句DELETE";return false;}if (sql.ToLower().IndexOf("update") > 0){msg= "查询参数中含有非法语句UPDATE";return false;}if (sql.ToLower().IndexOf("insert") > 0){msg= "查询参数中含有非法语句INSERT";return false;}return true;}//获取当前时间public staticDateTime NowTime{get{returnDateTime.Now;}}/// <summary>///将日期转换成字符串/// </summary>/// <param name="dt">日期</param>/// <returns>字符串</returns>public static string DateTimeConvertString(DateTime?dt){if (dt == null){return "";}else{returnConvert.ToDateTime(dt.ToString()).ToShortDateString();}}/// <summary>///将字符串转换成日期/// </summary>/// <param name="str">字符串</param>/// <returns>日期</returns>public static DateTime? StringConvertDatetime(stringstr){if (str == null){return null;}else{try{returnConvert.ToDateTime(str);}catch{return null;}}}public static stringGetUserIP(){if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];elsereturn System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];}} }
ResultHelper
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingApp.Common;usingApp.DAL;usingApp.IBLL;usingApp.Models;usingMicrosoft.Practices.Unity;namespaceApp.Admin {public static classLogHandler{[Dependency]public static ISysLogBLL logBLL { get; set; }/// <summary>///写入日志/// </summary>/// <param name="oper">操作人</param>/// <param name="mes">操作信息</param>/// <param name="result">结果</param>/// <param name="type">类型</param>/// <param name="module">操作模块</param>public static void WriteServiceLog(string oper, string mes, string result, string type, stringmodule){SysLog entity= newSysLog();entity.Id=ResultHelper.NewId;entity.Operator=oper;entity.Message=mes;entity.Result=result;entity.Type=type;entity.Module=module;entity.CreateTime=ResultHelper.NowTime;using (SysLogRepository logRepository = newSysLogRepository()){logRepository.Create(entity);}}} }
LogHandler
[HttpPost]publicJsonResult Create(SysSampleModel model){if(m_BLL.Create(model)){LogHandler.WriteServiceLog("虚拟用户", "Id:" + model.Id + ",Name:" + model.Name, "成功", "创建", "样例程序");return Json(1, JsonRequestBehavior.AllowGet);}else{LogHandler.WriteServiceLog("虚拟用户", "Id:" + model.Id + ",Name:" + model.Name, "失败", "创建", "样例程序");return Json(0, JsonRequestBehavior.AllowGet);}}
SysSampleController
同时App.Common要引用程序集System.Web
运行添加一条记录,然后打开我们的日志模块,OK,日志记录完成了,有点简单。
接下来是异常,上一讲说到,异常我们放在BLL中处理,然后我们把错误或者异常信息返回到Controller中被日志记录,当然异常他是在BLL层被记录的。
我们需要一个异常的集合类,来记录BLL层和DAL层,有时候DAL也要处理异常,所以我们也要用到ref 引用传递,貌似ref我们很喜欢,呵呵
见代码,在App.Common创建一个异常集合类
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceApp.Common {public classValidationError{publicValidationError() { }public string ErrorMessage { get; set; }}public class ValidationErrors : List<ValidationError>{/// <summary>///添加错误/// </summary>/// <param name="errorMessage">信息描述</param>public void Add(stringerrorMessage){base.Add(new ValidationError { ErrorMessage =errorMessage });}/// <summary>///获取错误集合/// </summary>public stringError{get{string error = "";this.All(a =>{error+=a.ErrorMessage;return true;});returnerror;} }} }
ValidationErrorHelper.cs
我们也要创建一个封装好的异常写入,类似与Log的LogHandler封装但我们放在BLL中,因为我们以后的其他项目的BLL要引用,这一步要考虑到。
在BLL中创建文件夹Core,写入以下类,BLL引用程序集System.Web里面用到了http的一些方法
usingSystem;usingSystem.Web.Configuration;usingApp.Models;usingSystem.IO;usingSystem.Text;usingApp.Common;namespaceApp.BLL.Core {/// <summary>///写入一个异常错误/// </summary>/// <param name="ex">异常</param>public static classExceptionHander{/// <summary>///加入异常日志/// </summary>/// <param name="ex">异常</param>public static voidWriteException(Exception ex){try{using (DBContainer db = newDBContainer()){SysException model= newSysException(){Id=ResultHelper.NewId,HelpLink=ex.HelpLink,Message=ex.Message,Source=ex.Source,StackTrace=ex.StackTrace,TargetSite=ex.TargetSite.ToString(),Data=ex.Data.ToString(),CreateTime=ResultHelper.NowTime};db.SysException.AddObject(model);db.SaveChanges();}}catch(Exception ep){try{//异常失败写入txtstring path = @"~/exceptionLog.txt";string txtPath = System.Web.HttpContext.Current.Server.MapPath(path);//获取绝对路径using (StreamWriter sw = new StreamWriter(txtPath, true, Encoding.Default)){sw.WriteLine((ex.Message+ "|" + ex.StackTrace + "|" + ep.Message + "|" +DateTime.Now.ToString()).ToString());sw.Dispose();sw.Close();}return;}catch { return; }}}}}
ExceptionHander
此异常当处理也异常时候,将在网站根目录下写入一个txt文件。
创建一个全局变量
ValidationErrors errors = new ValidationErrors();
我们要用引用传递,所以要修改IBLL和BLL的Create方法,如下
ISysSampleBLL : bool Create(ref ValidationErrors errors, SysSampleModel model);
SysSampleBLL :
/// <summary>///创建一个实体/// </summary>/// <param name="errors">持久的错误信息</param>/// <param name="model">模型</param>/// <returns>是否成功</returns>/// <summary>///创建一个实体/// </summary>/// <param name="errors">持久的错误信息</param>/// <param name="model">模型</param>/// <returns>是否成功</returns>public bool Create(refValidationErrors errors, SysSampleModel model){try{SysSample entity=Rep.GetById(model.Id);if (entity != null){errors.Add("主键重复");return false;}entity= newSysSample();entity.Id=model.Id;entity.Name=model.Name;entity.Age=model.Age;entity.Bir=model.Bir;entity.Photo=model.Photo;entity.Note=model.Note;entity.CreateTime=model.CreateTime;if (Rep.Create(entity) == 1){return true;}else{errors.Add("插入失败");return false;}}catch(Exception ex){errors.Add(ex.Message);ExceptionHander.WriteException(ex);return false;}}
修改Controller
[HttpPost]publicJsonResult Create(SysSampleModel model){if (m_BLL.Create(referrors, model)){LogHandler.WriteServiceLog("虚拟用户", "Id:" + model.Id + ",Name:" + model.Name, "成功", "创建", "样例程序");return Json(1, JsonRequestBehavior.AllowGet);}else{string ErrorCol =errors.Error;LogHandler.WriteServiceLog("虚拟用户", "Id:" + model.Id + ",Name:" + model.Name + "," + ErrorCol, "失败", "创建", "样例程序");return Json(0, JsonRequestBehavior.AllowGet);}}
注意:ExceptionHander.WriteException(ex);这里是写入异常信息
OK,你现在可以创建一条新的记录和插入一个ID大于50个字符的记录,让他记录日志和异常了。
显然我们的失败错误提示已经不符合国情了。我们返回的json格式是0和1我们要返回多个值了,比如1和成功创建,0和失败了啊,这样的2个值怎么办?
controller能把datagrid传过来的东西用类来接受,那么反过来想,js也能把controller发出去的值分解,创建一个序列化的类
在App.Common类库中创建JsonHandler帮助类,里面有2个重载,一个是返回3个值一个是2个值的。
所以当我们要返回订单的数量和总价格的时候,我们将用到类似的手段
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceApp.Common {public classJsonHandler{public static JsonMessage CreateMessage(int ptype,string pmessage,stringpvalue){JsonMessage json= newJsonMessage(){type=ptype,message=pmessage,value=pvalue};returnjson;}public static JsonMessage CreateMessage(int ptype, stringpmessage){JsonMessage json= newJsonMessage(){type=ptype,message=pmessage,};returnjson;}}public classJsonMessage{public int type{get;set;}public string message{get;set;}public string value{get;set;}} }
JsonHandler
再次修改Controller的Create
[HttpPost]publicJsonResult Create(SysSampleModel model){if (m_BLL.Create(referrors, model)){LogHandler.WriteServiceLog("虚拟用户", "Id:" + model.Id + ",Name:" + model.Name, "成功", "创建", "样例程序");return Json(JsonHandler.CreateMessage(1, "插入成功"), JsonRequestBehavior.AllowGet);}else{string ErrorCol =errors.Error;LogHandler.WriteServiceLog("虚拟用户", "Id:" + model.Id + ",Name:" + model.Name + "," + ErrorCol, "失败", "创建", "样例程序");return Json(JsonHandler.CreateMessage(0, "插入失败" +ErrorCol), JsonRequestBehavior.AllowGet);}}
修改SysSample的Create的JS部分
<script type="text/javascript">$(function () {$("#btnSave").click(function () {if ($("#CreateForm").valid()) {$.ajax({url:"/SysSample/Create",type:"Post",data: $("#CreateForm").serialize(),dataType:"json",success: function (data) {if (data.type == 1) {window.parent.frameReturnByMes(data.message);window.parent.frameReturnByReload(true);window.parent.frameReturnByClose()}else{window.parent.frameReturnByMes(data.message);}}});}return false;});});</script>
由于时间关系,这一讲就先到这里吧!这一讲其实比较仓促。不懂的留言
你需要继续做的就是在删除,编辑等操作也加入这些的。这点留给大家自己表现吧....
下一讲是全局异常的捕获。
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(12)-系统日志和异常的处理②...相关推荐
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(31)-MVC使用RDL报表
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(31)-MVC使用RDL报表 这次我们来演示MVC3怎么显示RDL报表,坑爹的微软把MVC升级到5都木有良 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(32)-swfupload多文件上传[附源码]...
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(32)-swfupload多文件上传[附源码] 文件上传这东西说到底有时候很痛,原来的asp.net服务器 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(39)-在线人数统计探讨
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(39)-在线人数统计探讨 系列目录 基于web的网站在线统计一直处于不是很精准的状态!基本上没有一种方法可 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(34)-文章发布系统①-简要分析...
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(34)-文章发布系统①-简要分析 原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(13)-系统日志和异常的处理③
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(13)-系统日志和异常的处理③ 参考文章: (1)构建ASP.NET MVC4+EF5+EasyUI+Unity ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(10)-系统菜单栏[附源码]
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(10)-系统菜单栏[附源码] 原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】...
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-[过滤器+Cache] 原文:构建ASP.NET MVC4+EF5+EasyUI+ ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单...
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单 原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(36)-文章发布系统③-kindeditor使用...
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(36)-文章发布系统③-kindeditor使用 原文:构建ASP.NET MVC4+EF5+EasyUI+Un ...
最新文章
- Android开发者指南(22) —— Accessing Resources
- winform 界面 xml化_FlinkSQL 1.11 on Zeppelin平台化实践
- 收藏 | AI领域必看的45篇论文(附下载地址)
- iOS系统网络抓包方法
- JSOI2010 联通数
- StandardWrapper ...$$EnhancerByCGLIB$$b9
- 字符编码的前世今生--转
- python装饰器模块加载后的若干解释
- TensorFlow学习笔记之六(循环神经网络RNN)
- sun.misc.Unsafe和堆外内存
- BaseYii_autoload
- .net应用程序中添加chm帮助文档打开显示此程序无法显示网页问题
- 学习笔记 04----声明和类
- 【AD】mm,mile,inch+电流大小同线宽关系
- qt添加qwt帮助文件_qt creator中使用qwt插件
- Java中判断一个字符串全为数字和字母
- 如何正确 Get 分库分表?
- 绝不因寂寞而爱上别人
- 重磅!原清华副校长任职南科大校长:他考研三次,读博七年,想做科研人偶像...
- 消息摘要(Message Digest)及其算法
热门文章
- ps怎么把一个颜色替换成另一个颜色_图标设计,用PS制作一款小清新的拟物时钟...
- android 多个占位符,Android多语言支持:由于占位符计数不同导致的字符串格式问题...
- array用法 numpy_NumPy总结(基础用法)
- Fade 数字切换动效
- 运行PHP出现No input file specified错误解决办法
- 从 Java 到 Scala(二):object
- Visual Studio Extensions for SharePoint v1.1
- Java云托管服务的开支削减策略
- HTML5 监听当前位置
- AutoFac Ioc依赖注入容器