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