using Magic.Tool;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
//MVC中全局错误拦截
namespace Magic.Mvc
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
/// <summary>
/// 全局错误处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
var error = "";
try
{
Exception exception = Server.GetLastError();
error = exception != null ? exception.Message : "";
Response.Clear();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
// Page not found.
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// Server error.
routeData.Values.Add("action", "HttpError500");
break;
// Here you can handle Views to other error codes.
// I choose a General error template
default:
routeData.Values.Add("action", "General");
break;
}
}
// Pass exception details to the target error View.
routeData.Values.Add("error", exception.Message);
// Clear the error on server.
Server.ClearError();
// Call target Controller and pass the routeData.
IController errorController = new Controllers.ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
catch (Exception ex)
{
LogHelper.Log(ex.Message);
}
finally
{
LogHelper.Log("全局捕获错误 " + error);
}
}
}
}
using System.Web.Mvc;
namespace Magic.Mvc.Controllers
{
/// <summary>
/// 统一错误处理
/// </summary>
public class ErrorController : Controller
{
public ActionResult Index(string error)
{
var errorTitle = "网站内部错误,请稍后再尝试";
ViewData["Title"] = errorTitle;
ViewData["Description"] = error;
//return View("Index");
return Content(errorTitle, null, System.Text.Encoding.GetEncoding("GB2312"));
}
public ActionResult HttpError404(string error)
{
var