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 自定义错误处理的更多相关文章

  1. ASP.net MVC自定义错误处理页面的方法

    在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...

  2. MVC自定义错误页404静态页

    昨天公司要求给所有项目添加自定义404错误页,具体的要求实现的有以下几点: 1.实现自定义错误(如各种error,404等)跳转到指定的页面 2.所指定的页面输出的http状态值必须是404或其他指定 ...

  3. ASP.NET MVC 自定义错误页面心得

    自定义错误页面的目的,就是为了能让程序在出现错误/异常的时候,能够有较好的显示体验. 所以,首先要先了解,我们可以在哪里捕获异常. 当程序发生错误的时候,我们可以在两个地方捕获: Global里面的A ...

  4. 在ASP.NET MVC自定义错误页面

    异常处理跳转页面 第一步,在项目的Web.config文件中找到节点<system.web> 在此节点下添加配置(Error为定义的控制器也可以多添加些error标签用于区分不同的错误) ...

  5. MVC 自定义 错误页面

    很多时候,我们需要自定义错误页面,用来当发生异常后引导用户进入一个比较友好的错误页面. 在这里,我归结一下我常用的2个方案 1   通过Global.asax 文件来处理异常信息(这个不管是 MVC ...

  6. .NET MVC自定义错误处理页面的方法

    在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...

  7. MVC自定义错误页面

    MVC异常处理主要有三种方案:1.基于HandleErrorAttribute重写OnException方法:2.基于Global.apsx添加Application_Error方法:3.直接在Web ...

  8. MVC自定义错误日志异常处理

    MVC添加错误日志处理模块很简单,只要写个继承自HandleErrorAttribute的过滤器,重新OnException方法,贴个异常处理代码如下: public class ExceptionA ...

  9. Asp.net MVC 自定义错误页面以及return HttpNotFound遇到的问题

    今天在处理mvc 项目404和500页面时,发现我以前比较喜欢用的Return HttpNotFound()没有跳转到我在webconfig中配置的自定义404页面,而且也不会去执行Global中的A ...

随机推荐

  1. 【VC编程技巧】文件☞2.3CArchive的用法

    CArchive 对象提供了一个类型安全缓冲机制CArchive 对象提供了一个类型安全缓冲机制.用于将可序列化对象写入CFile 对象或从中读取可序列化对象.通常,CFile 对象表示磁盘文件:但是 ...

  2. 【转】Android API 中文(14) —— ViewStub

    用一个XML源填充view.inflate(上下文对象,资源文件Id,父窗口组一般为null): 原文网址:http://www.cnblogs.com/over140/archive/2010/10 ...

  3. bzoj1619[Usaco2008 Nov]Guarding the Farm 保卫牧场

    Description The farm has many hills upon which Farmer John would like to place guards to ensure the ...

  4. socket pro

    /etc/exports/tmp目录共享为任何人可以共享并可以进行读写操作 /tmp *(rw,no_root_squash) /home/test 192.168.1.*(rw) *(ro) /et ...

  5. 在 Ubuntu 12.04 上安装 GitLab6.0

    安装环境: 操作系统:    Ubuntu 12.4 LTS 英文 数据库:        mysql5.5.32 web服务器: nginx1.4.1 首先, 添加git和nginx的ppa,并升级 ...

  6. iOS开发:深入理解GCD 第一篇

    最近把其他书籍都放下了,主要是在研究GCD.如果是为了工作,以我以前所学的GCD.NSOperation等知识已经足够用了,但学习并不仅仅知识满足于用它,要知其然.并且知其所以然,这样才可以不断的提高 ...

  7. 蓝桥杯 BASIC 24 龟兔赛跑预測(模拟)

    [思路]:模拟.注意一个是在兔子歇息的时间乌龟可能到达了.刚開始没考虑WA80%. [AC代码]: #include <iostream> #include <algorithm&g ...

  8. JMeter简单的性能测试实例

    JMeter基础之——一个简单的性能测试 我们了解了jmeter的一此主要元件,那么这些元件如何使用到性能测试中呢.这一节创建一个简单的测试计划来使用这些元件.该计划对应的测试需求. 1)测试目标网站 ...

  9. 完善GDAL与OpenCV间的数据格式转换与影像分块读写

    本博客为原创内容,未经博主允许禁止转载,商用,谢谢. 一.前言 关于GDAL与openCV间的数据格式转换,在我之前的博客中已有简要说明,这里,由于最近工作上经常用到openCV里的函数进行图像处理, ...

  10. VMware SphereESXi上安装虚拟机

    VMware SphereESXi上安装虚拟机 创建新虚拟机 此处以CentOS为例 注意:配置上传的系统文件位置及启动项