【问题标题】:Custom 403 error page in MVC4 not showingMVC4 中的自定义 403 错误页面未显示
【发布时间】:2013-07-13 05:34:22
【问题描述】:

我已通过以下方式设置我的Web.config 以显示自定义 403 错误页面,但由于某种原因该页面未显示 - 我仍然得到默认错误页面! 404 的自定义页面正确显示,它使用相同的 ErrorController

Web.Config

<customErrors mode="On" defaultRedirect="~/Error">
  <error redirect="~/Error/NotFound" statusCode="404" />
  <error redirect="~/Error/Forbidden" statusCode="403"  />
</customErrors>

错误控制器

public class ErrorController : BaseController
{
    public ViewResult Forbidden()
    {
        Response.StatusCode = 403;  //you may want to set this to 200
        return View("Error403");
    }
}

产生 403 的属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeEMAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

【问题讨论】:

  • 你的Forbidden函数不应该返回ActionResult而不是ViewResult吗?
  • 该功能甚至没有被击中!
  • 那么,您的filterContext.HttpContext.Request.IsAuthenticated 是这里的问题,可以在if 之前检查filterContext.HttpContext.User.Identity 以获得更多线索??
  • 为什么会出现这个问题? if 工作正常...
  • 这个问题的答案是什么?我面临着完全相同的问题。

标签: c# asp.net-mvc error-handling http-status-code-403 custom-error-pages


【解决方案1】:
 <customErrors mode="On" defaultRedirect="~/Error/Error.html" redirectMode="ResponseRewrite">
      <error redirect="~/Error/403.aspx" statusCode="403" />
      <error redirect="~/Error/404.aspx" statusCode="404" />
      <error redirect="~/Error/500.html" statusCode="500" />
    </customErrors>

在根目录“错误”中创建​​页面403.aspx

     <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>403 Not Found</title>
</head>
<body>
    <%
    Server.ClearError();
Response.Status = "403 - Forbidden: Access is denied.";
Response.StatusCode = 403;
         %>
    <div>
    <h2>403 - Forbidden: Access is denied.</h2>
    </div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    相关资源
    最近更新 更多