MVC 自定义错误处理
1. Application_Error
namespace Libaray.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
LogHelper.LoadConfig(Server.MapPath("~/Web.config"));
//log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
}
protected void Application_Error(object sender, EventArgs e)
{
var lastError = Server.GetLastError();
if (lastError != null)
{
var httpError = lastError as HttpException;
if (httpError != null)
{
//Server.ClearError();
switch (httpError.GetHttpCode())
{
case 404:
Response.Redirect("/Exception/NotFound");
break;
}
}
}
}
}
}
2. 自定义的Exception处理
1) 注册
using System.Web;
using System.Web.Mvc;
namespace Libaray.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new Libaray.Web.LibAttri.LogExceptionAttribute(), 1);
filters.Add(new HandleErrorAttribute(),2);
}
}
}
2)定义类
namespace Libaray.Web.LibAttri
{
public class LogExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
string broser = request.Browser.Browser;
string broserVersion = request.Browser.Version;
string system = request.Browser.Platform;
//string sMessage = filterContext.Exception.Message;
string sMessage = string.Format("消息类型:{0},消息内容:{1}, 引发异常的方法:{2}, 引发异常源:{3}",
filterContext.Exception.GetType().Name,
filterContext.Exception.InnerException.Message,
filterContext.Exception.TargetSite,
filterContext.Exception.Source +
filterContext.Exception.StackTrace);
string errBaseInfo = string.Format("UserId={0},Broser={1},BroserVersion={2},System={3},Controller={4},Action={5},Error={6}", "", broser, broserVersion, system, controllerName, actionName,sMessage);
LogHelper.Error(errBaseInfo);
filterContext.Controller.TempData["ExceptionMessage"] = sMessage;
filterContext.Result = new RedirectResult("/Exception/Error");
}
}
}
3. Exception Controller
namespace Libaray.Web.Controllers
{
public class ExceptionController : Controller
{
public ActionResult NotFound()
{
return View();
}
public ActionResult Error()
{
ViewBag.Error = TempData["ExceptionMessage"];
return View();
}
}
}
4. View
@{
ViewBag.Title = "Error";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row" style="margin-top:10px;">
<div class="col-sm-5">
<h3>错误</h3>
<div class="alert alert-info">
<p>对不起,访问出现错误。</p>
</div>
<a href="/Home/Index" class="btn btn-sm btn-primary">返回首页</a>
</div>
</div>
@{
ViewBag.Title = "访问出错";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row" style="margin-top:10px;">
<div class="col-sm-5">
<h3>访问资源出错</h3>
<div class="alert alert-info">
<p>对不起,我们无法找到指定页面,请确认访问地址是否输入正确。</p>
</div>
<a href="/Home/Index" class="btn btn-sm btn-primary">返回首页</a>
</div>
</div>
5. Webconfig
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<customErrors mode="On">
</customErrors>
</system.web>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Libaray.Web
{
public class LogHelper
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static void LoadConfig(string path)
{
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(path));
} /// <summary>
/// 错误信息
/// </summary
public static void Error(string error)
{
log.Error(error);
} /// <summary>
/// 致命信息
/// </summary>
public static void Fatal(string fatal)
{
log.Fatal(fatal);
} /// <summary>
/// 一般信息
/// </summary>
public static void Info(string info)
{
log.Info(info);
} /// <summary>
/// 警告信息
/// </summary>
public static void Warn(string warn)
{
log.Warn(warn);
}
}
}
MVC 自定义错误处理的更多相关文章
- ASP.net MVC自定义错误处理页面的方法
在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...
- MVC自定义错误页404静态页
昨天公司要求给所有项目添加自定义404错误页,具体的要求实现的有以下几点: 1.实现自定义错误(如各种error,404等)跳转到指定的页面 2.所指定的页面输出的http状态值必须是404或其他指定 ...
- ASP.NET MVC 自定义错误页面心得
自定义错误页面的目的,就是为了能让程序在出现错误/异常的时候,能够有较好的显示体验. 所以,首先要先了解,我们可以在哪里捕获异常. 当程序发生错误的时候,我们可以在两个地方捕获: Global里面的A ...
- 在ASP.NET MVC自定义错误页面
异常处理跳转页面 第一步,在项目的Web.config文件中找到节点<system.web> 在此节点下添加配置(Error为定义的控制器也可以多添加些error标签用于区分不同的错误) ...
- MVC 自定义 错误页面
很多时候,我们需要自定义错误页面,用来当发生异常后引导用户进入一个比较友好的错误页面. 在这里,我归结一下我常用的2个方案 1 通过Global.asax 文件来处理异常信息(这个不管是 MVC ...
- .NET MVC自定义错误处理页面的方法
在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...
- MVC自定义错误页面
MVC异常处理主要有三种方案:1.基于HandleErrorAttribute重写OnException方法:2.基于Global.apsx添加Application_Error方法:3.直接在Web ...
- MVC自定义错误日志异常处理
MVC添加错误日志处理模块很简单,只要写个继承自HandleErrorAttribute的过滤器,重新OnException方法,贴个异常处理代码如下: public class ExceptionA ...
- Asp.net MVC 自定义错误页面以及return HttpNotFound遇到的问题
今天在处理mvc 项目404和500页面时,发现我以前比较喜欢用的Return HttpNotFound()没有跳转到我在webconfig中配置的自定义404页面,而且也不会去执行Global中的A ...
随机推荐
- 外部函数接口 LibFFI
“FFI” 的全名是 Foreign Function Interface,通常指的是允许以一种语言编写的代码调用另一种语言的代码.而 “Libffi” 库只提供了最底层的.与架构相关的.完整的”FF ...
- 2015第19周四jquery版本
今天用到一个jquery插件,发现最新版需要jquery2.0以上版本才行,而目前项目在用的版本是1.8.3,自然无法使用,刚看了jquery的主要版本和差异,直接百度搜索无满意结果,最后在百科中给出 ...
- (Data structure)Implement Trie && Add and Search Word
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...
- HDU4821---字符串hash,map判重
这是2013年长春区域赛的铜牌题...然而第一次做的时候一直觉得会超时的..最后才知道并没有想象中的那么恐怖: 这题有两个注意的地方: (1)h[i] = h[i-1] * seed + s[i] - ...
- Saruman's Army (POJ 3069)
直线上有N个点.点i的位置是Xi.从这N个点中选择若干个,给它们加上标记.对每一个点,其距离为R以内的区域里必须又带有标记的点(自己本身带有标记的点,可以认为与其距离为0的地方有一个带有标记的点).在 ...
- c语言结构体1之定义
这是在复习阶段随便小结的一些东西 别喷哦 结构体定义的三种方式 注意事项: 1结构体括号后面有分号 2#define得放在程序上面 3成员名可以和结构体名相同 4结构体类型不能直接访问成员,也不能赋值 ...
- phpcms:六、频道页(category.html)
1.当前栏目的ID:{$catid}标题样式:{title_style($v[style])}(在添加内容或编辑内容的时候,标题右边 有一个选择颜色的块).{str_cut(strip_tags($v ...
- laravel-模板引擎Blade
(慕课网_轻松学会Laravel-基础篇_天秤vs永恒老师) 一.概述 Blade是Laravel提供的一个既简单又强大的模板引擎 和其他流行的PHP模板引擎不一样,Blade并不限制你在视图view ...
- C++11 多线程 教学(2)
C++11开始支持多线程编程,之前多线程编程都需要系统的支持,在不同的系统下创建线程需要不同的API如pthread_create(),Createthread(),beginthread()等, ...
- UITableView的简单总结与回顾
今天突发奇想的想对UItableView做一下汇总,感觉在编程中这个控件可以千变万化也是用的最多的一个了,下面就为大家简单总结下这个控件,也许还有不足,不过还是请各位不吝赐教了哈,那么我就开始了,我会 ...