I have two custom error pages; 404 and 401. 404 is working as intended, but 401 error is navigating to 404 error page. So whenever I click on a page when I'm not logged in I want it to show the 401 error, non-authorized. It keeps showing the wrong error page, which is NotFound.cshtml (404).
This is my 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"
};
}
}
}
}
Error Controller
[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>
Root 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>