首页 > 解决方案 > 非授权自定义页面不起作用

问题描述

我有两个自定义错误页面;404 和 401。404 正在按预期工作,但 401 错误正在导航到 404 错误页面。因此,每当我在未登录时单击页面时,我希望它显示 401 错误,未经授权。它一直显示错误的错误页面,即 NotFound.cshtml (404)。

这是我的 UserAuthenticationFilter

{
    public class UserAuthenticationFilter : ActionFilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            // Check session is empty then set as result is HttpUnauthorizedResult
            if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserId"])))
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "NonSecure"
                };
            }
        }

    }
}

错误控制器

[HandleError]
    public class ErrorController : Controller
    {
        public ActionResult Error()
        {
            return View();
        }
        public ActionResult NotFound()
        {
            return View();
        }
        public ActionResult NonSecure()
        {
            return View();
        }
    }
}

NonSecure.cshtml

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "NonSecure";
}

<div style="background-color: #A52A2A; color: White; height: 10px;">
</div>
<div style="background-color: #F5F5DC; color: red; height: 170px;">
    <div style=" padding:20px;">
        <h4>
            Sorry, the page you are looking for is authorized. You need to login!
        </h4>
        <h6>@Html.ActionLink("Go Back To Home Page", "Login", "User")</h6>
        <br />
        <br />
    </div>
</div>
<div style="background-color: #A52A2A; color: White; height: 20px;">
</div>

根 Web.config

<system.web>
    <customErrors mode="On" redirectMode="ResponseRedirect">
      <error statusCode="404" redirect="~/Error/NotFound"/>
      <error statusCode="401" redirect="~/Error/NonSecure"/>
    </customErrors>
    <authentication mode="Forms">
      <forms timeout="2800"></forms>
    </authentication>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <globalization uiCulture="en-US" />
  </system.web>

标签: c#asp.netmodel-view-controller

解决方案


推荐阅读