我正在使用RC2
使用URL路由:
routes.MapRoute(
"Error",
"{*url}",
new { controller = "Errors", action = "NotFound" } // 404s
);
Run Code Online (Sandbox Code Playgroud)
以上似乎照顾这样的请求(假设默认路由表由初始MVC项目设置):"/ blah/blah/blah/blah"
覆盖控制器本身中的HandleUnknownAction():
// 404s - handle here (bad action requested
protected override void HandleUnknownAction(string actionName) {
ViewData["actionName"] = actionName;
View("NotFound").ExecuteResult(this.ControllerContext);
}
Run Code Online (Sandbox Code Playgroud)
但是,之前的策略不处理对Bad/Unknown控制器的请求.例如,我没有"/ IDoNotExist",如果我请求这个,我从Web服务器获取通用404页面而不是我的404,如果我使用路由+覆盖.
最后,我的问题是: 有没有办法在MVC框架中使用路由或其他东西来捕获这种类型的请求?
或者我应该默认使用Web.Config customErrors作为我的404处理程序并忘记所有这些?我假设如果我使用customErrors,由于Web.Config对直接访问的限制,我必须在/ Views之外存储通用404页面.
我想要显示500,404和403的自定义错误页面.这是我所做的:
在web.config中启用了自定义错误,如下所示:
<customErrors mode="On"
defaultRedirect="~/Views/Shared/Error.cshtml">
<error statusCode="403"
redirect="~/Views/Shared/UnauthorizedAccess.cshtml" />
<error statusCode="404"
redirect="~/Views/Shared/FileNotFound.cshtml" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)HandleErrorAttribute
在FilterConfig
类中注册为全局动作过滤器,如下所示:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomHandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
Run Code Online (Sandbox Code Playgroud)为上述每条消息创建了自定义错误页面.500的默认值已经开箱即用.
在每个自定义错误页面视图中声明该页面的模型 System.Web.Mvc.HandleErrorInfo
对于500,它显示自定义错误页面.对于其他人,它没有.
有什么我想念的吗?
看起来这并不是显示自定义错误的全部内容,因为我OnException
在HandleErrorAttribute
类的方法中读取代码并且它只处理500.
我该怎么做才能处理其他错误?
当我的ASP.NET MVC 4应用程序发生错误时,我想根据错误类型为用户自定义视图.例如,找不到页面或发生异常(包含有关异常的一些用户友好的详细信息).我已经检查了如何在StackOverflow和其他在线资源上执行此操作的其他示例,但没有一个答案对我有用.
VS2012中的基本[HandleError]属性似乎不适用于面向.NET 4.5的MVC 4应用程序.这是我家控制器中的代码:
[HandleError]
public ActionResult Index()
{
Response.TrySkipIisCustomErrors = true; //doesn't work with or without this
throw new NullReferenceException("Uh oh, something broke.");
}
Run Code Online (Sandbox Code Playgroud)
它只是抛出异常,我希望由于[HandleError]属性而返回默认的〜/ Shared/Error.cshtml视图,但我得到的是HTTP 500内部服务器错误,表明该页面不能显示.我检查了我的web.config,不同的配置似乎表现得很奇怪.在该部分中,它目前包含:
<customErrors mode="On" />
Run Code Online (Sandbox Code Playgroud)
(我已经尝试添加defaultRedirect并使用customErrors mode ="Off"但是没有任何效果...我正在渲染共享错误视图或CustomError视图.如果我将customErrors模式更改为关闭,然后我可以看到预期的异常细节,所以它正在抛出"呃哦,有点破坏"的例外.
我也尝试将一个OnException处理程序添加到HomeController,虽然我可以调试并看到正在引发OnException事件,但它没有任何区别:
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
filterContext.ExceptionHandled = true;
if (filterContext == null)
{
filterContext.Result = View("CustomError");
return;
}
Exception e = filterContext.Exception;
// TODO: Log the exception here
ViewData["Exception"] = e; // pass the exception to the view
filterContext.Result = View("CustomError"); …
Run Code Online (Sandbox Code Playgroud)