【问题标题】:Custom Error redirection does not work in ASP.NET MVC Web.Config自定义错误重定向在 ASP.NET MVC Web.Config 中不起作用
【发布时间】:2014-04-08 09:02:20
【问题描述】:

在我的应用程序中,我在 Web.config 中包含了<customerror> 标记,如下所示:

<customErrors mode="On">
  <error statusCode="404" redirect="/Error/404"/>
  <error statusCode="403" redirect="/Error/403"/>
  <error statusCode="500" redirect="/Error/500"/>
</customErrors>

我在路由配置中创建了一个条目,这样任何带有 url 模式 /Error/{status} 的请求都会以 status 作为参数的特定控制器操作.

我有一个自定义的 ActionFilterAttribute 来检查用户是否是管理员,如果不是则返回 HTTP 403 结果。以下是我的自定义过滤器属性。

public class RequireAdminAttribute: ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (!UserOperations.IsAdmin())
        {
            filterContext.Result = new Http403Result();
        }
    }
}

internal class Http403Result : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        // Set the response code to 403.
        context.HttpContext.Response.StatusCode = 403;
    }
}

现在,如果用户未经授权,我需要将用户重定向到 /Error/403 页面。当我运行我的应用程序时,当发生 403 错误时,我的应用程序不会重定向到错误页面。如果发生 404 错误,它会重定向到给定的 404 错误页面(在大多数情况下发生 404 时)。这是什么原因?谁能给我一个解决方案?我是否需要使用 RedirectToRouteResult 之类的东西硬编码重定向到错误页面?

编辑: 在某些情况下,重定向在我明确使用 return HttpNotFound(); 结果的情况下也不起作用。我想知道使用return HttpNotFound(); 是否不会重定向到自定义页面。

谢谢。

【问题讨论】:

标签: asp.net-mvc custom-error-pages


【解决方案1】:

尝试将此添加到您的Web.config

<system.webServer>
  <httpErrors existingResponse="Replace" errorMode="Custom"  defaultResponseMode="Redirect">
    <remove statusCode="403"/>
    <error responseMode="ExecuteURL" statusCode="403" path="/Error/403" />
  </httpErrors>
</system.webServer>

【讨论】:

  • 我将您在error 标记中的答案中提到的路径attribute 替换为/Error/403 并重试。但没有运气。
  • 结果如何?另外,什么版本的 IIS?
  • 它的IIS 8,仍然显示详细的错误页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 2020-12-23
  • 2011-06-14
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多