c# - 非授权自定义页面不起作用
问题描述
我有两个自定义错误页面;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>
解决方案
推荐阅读
- python - 使用 SimPy 的 AnyOf 方法时如何知道正在使用哪个资源?
- sap-basis - SAP Webdynpro 应用程序导致恢复时出现会话错误
- android - 如果使用 maxLines、textAppearanceBody1 和重力结束,文本会被剪切
- android - 使用 Bitbucket 发布 Android Gradle 库(Atifact)
- tensorflow - 从 TF 模型 Zoo 导入模型并进行训练
- angular - 是否可以从开发者模块延迟加载组件?
- r - 摆脱使用正则表达式 data.table 选择列时找不到的模式
- laravel - 在 whereHas 的数据透视表中执行 where 子句
- php - 我正在尝试在 wordpress 中添加自定义路由
- python - 无法从另一个文件导入 1 个变量,但可以导入其他变量