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. sqlplus与sqlplusw (转)

    一.sqlplus与sqlplusw两者统称SQLPlus,是Oracle的一个命令行执行工具.   二.SQLPlus的有两种运行方式: 1.在命令行窗口运行.sqlplus 2.在窗口中运行.sq ...

  2. 2015第24周一Spring事务

    1. Spring事务管理简介 (1)Spring为多种不同类型的事务管理机制提供统一编程模型,这些事务管理模型包括JTA.JDBC.Hibernate.JPA和JDO. (2)Spring支持声明式 ...

  3. .net中除去IList中的多余项

    IList<ActionInfo> tempList = new List<ActionInfo>(); IList<ActionInfo> tempActionL ...

  4. poj1284:欧拉函数+原根

    何为原根?由费马小定理可知 如果a于p互质 则有a^(p-1)≡1(mod p)对于任意的a是不是一定要到p-1次幂才会出现上述情况呢?显然不是,当第一次出现a^k≡1(mod p)时, 记为ep(a ...

  5. hdu5045:带权二分图匹配

    题目大意 : n个人 做m道题,其中 每连续的n道必须由不同的人做 已知第i人做出第j题的概率为pij,求最大期望 思路:考虑每连续的n道题 都要n个人来做,显然想到了带权的二分图匹配 然后就是套模板 ...

  6. 深入浅出 消息队列 ActiveMQ

    http://blog.csdn.net/jwdstef/article/details/17380471

  7. 为什么新建的管理员账号权限没有Administrator大?

    Administrator是超级管理员,UAC不用确认,跟关了一样. 新建隶属于administrator组的用户,可以关掉UAC. 控制面板>系统和安全>操作中心>更改用户帐户控制 ...

  8. EL表达式 functions String处理函数

    01.uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>  02.上面的 uri 根据 ...

  9. ZigBee心电传输(二)

    不管怎样,还是在高手的帮助下完成了前面的硬件部分,现在进行ZigBee的心电AD采集和转换.需要把ZigBee重新拾起来. 首先明确下目标和思路吧,目标是将模拟心电信号通过AD转换,变为数字信号,再用 ...

  10. vsim仿真VHDL输出fsdb格式文件

    vsim(modelsim)仿真VHDL输出fsdb格式文件 1.Dump准备 (1) 将下列设置放到顶层testbench tb.vhd文件中[注意放置的位置:关系如图] library novas ...