代码改变世界

ASP.NET MVC 3 中,自定义全局的错误处理页面

2011-04-07 15:49  音乐让我说  阅读(2594)  评论(7编辑  收藏  举报

Global.asax 中

        protected void Application_Error(object sender, EventArgs e)
        {
            if (!HttpContext.Current.IsCustomErrorEnabled)
            {
                return;
            }

            var exception = Server.GetLastError();
            var httpException = new HttpException(null, exception);

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");
            routeData.Values.Add("httpException", httpException);

            Server.ClearError();

            var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(
                new RequestContext(new HttpContextWrapper(Context), routeData), "Error");

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }

 然后创建ErrorController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using NBlog.Web.Application;
using NBlog.Web.Application.Service;

namespace NBlog.Web.Controllers
{
    public partial class ErrorController : LayoutController
    {
        public ErrorController(IServices services) : base(services) { }

        public ActionResult Index()
        {
            var model = new ErrorModel();
            var httpException = RouteData.Values["httpException"] as HttpException;

            var httpCode = (httpException == null) ? 500 : httpException.GetHttpCode();

            switch (httpCode)
            {
                case 403:
                    Response.StatusCode = 403;
                    model.Heading = "Forbidden";
                    model.Message = "You aren't authorised to access this page.";
                    break;
                case 404:
                    Response.StatusCode = 404;
                    model.Heading = "Page not found";
                    model.Message = "We couldn't find the page you requested.";
                    break;
                case 500:
                default:
                    Response.StatusCode = 500;
                    model.Heading = "Error";
                    model.Message = "Sorry, something went wrong.  It's been logged.";
                    break;
            }
            
            Response.TrySkipIisCustomErrors = true;

            return View(model);
        }
    }
}

ErrorModels.cs

namespace MvcHandlerGlobalError.Models
{
    public class ErrorModels
    {
        /// <summary>
        /// 网页标题
        /// </summary>
        public string Heading { get; set; }

        /// <summary>
        /// 网页内容
        /// </summary>
        public string Message { get; set; }
    }
}

 最后注意要在 Web.config 中启用自定义错误

    <!-- 启用自定义错误 -->
    <customErrors mode="On">
    </customErrors>

Index.cshtml

@model MvcHandlerGlobalError.Models.ErrorModels

@{
    ViewBag.Title = Model.Heading;
}
<div>
    <h1>@Model.Heading</h1>
    <p>@Model.Message</p>
    <p>@Html.ActionLink("Continue »", "Index", "Home")</p>
</div>

最后测试 ,输入一个不存在的 URL ,比如:http://localhost:2458/Home/MyAbout

谢谢浏览!