ASP.NET MVC4 CustomErrors DefaultRedirect被忽略 [英] ASP.NET MVC4 CustomErrors DefaultRedirect Ignored
问题描述
我有一个MVC 4应用程序,使用自定义HandleErrorAttribute来仅处理自定义异常.我想截取默认的404和其他非500错误页面,并用更具吸引力的内容替换它们.为此,我在Web.config中添加了以下内容:
I have an MVC 4 app, using a custom HandleErrorAttribute to handle only custom exceptions. I would like to intercept the default 404 and other non-500 error pages and replace them with something more attractive. To that end, I added the following to my Web.config:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error/Index" />
...
</ system.web>
我有一个带有Index方法和相应视图的Error控制器,但仍然得到默认的404错误页面.我也尝试将defaultRedirect
设置为静态html文件无济于事.我尝试在<customErrors>
内部添加特定于404的错误处理,甚至尝试以编程方式修改路由,所有操作均无结果.我想念什么?为什么ASP会忽略我的默认错误处理?
I have an Error controller with an Index method and corresponding view, but still I get the default 404 error page. I have also tried setting my defaultRedirect
to a static html file to no avail. I have tried adding error handling specific to 404's inside <customErrors>
, and I even tried modifying the routes programattically, all with no results. What am I missing? Why is ASP ignoring my default error handling?
注意:我之前注意到,即使使用<customErrors mode="On"
,也无法在本地测试CustomHandleErrorAttribute.但是,当我从开发箱中将其放在服务器上时,它确实可以工作...不知道是否相关. 这个家伙有相同的问题.
Note: I noticed earlier that I cannot test my CustomHandleErrorAttribute locally, even with <customErrors mode="On"
. It does work when I hit it on my server from my dev box though... not sure if that is related. This guy had the same problem.
推荐答案
这应该有效:
1. 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>
2.如下所示,将HandleErrorAttribute注册为FilterConfig类中的全局操作过滤器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomHandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
如果那不起作用,请尝试通过检查状态代码(例如Global.asax中的以下代码)来使自己转移响应:至少它必须起作用.
If that dont work then, Try to make yourself transfer the response by checking status codes like the Following in the Global.asax: at least it must work.
void Application_EndRequest(object sender, EventArgs e)
{
if (Response.StatusCode == 401)
{
Response.ClearContent();
Server.Transfer("~/Views/Shared/UnauthorizedAccess.cshtml");
}
}
这篇关于ASP.NET MVC4 CustomErrors DefaultRedirect被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!