Hai*_*der 29 asp.net-mvc custom-error-pages custom-errors
我在ASP.NET MVC 5应用程序中使用自定义authorize属性,如下所示:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAuthenticated)
{
context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在system.web我的web.config部分,我提到了错误路径,如:
<system.web>
<customErrors mode="On" defaultRedirect="/Error/Error">
<error statusCode="403" redirect="/Error/NoPermissions"/>
</customErrors>
</system.web>
Run Code Online (Sandbox Code Playgroud)
但我从未被重定向到我的自定义错误页面/Error/NoPermissions.相反,浏览器显示"HTTP错误403.0 - 禁止"的常规错误页面.
ubi*_*404 44
[1]:从Web.config中删除所有'customErrors'和'httpErrors'
[2]:检查'App_Start/FilterConfig.cs'如下所示:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
Run Code Online (Sandbox Code Playgroud)
[3]:在'Global.asax'中添加此方法:
public void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "ErrorPage");
routeData.Values.Add("action", "Error");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
Response.TrySkipIisCustomErrors = true;
IController controller = new ErrorPageController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
}
Run Code Online (Sandbox Code Playgroud)
[4]:添加'Controllers/ErrorPageController.cs'
public class ErrorPageController : Controller
{
public ActionResult Error(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
ViewBag.StatusCode = statusCode + " Error";
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
[5]:在'Views/Shared/Error.cshtml'中
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}
<h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>
//@Model.ActionName
//@Model.ControllerName
//@Model.Exception.Message
//@Model.Exception.StackTrace
Run Code Online (Sandbox Code Playgroud)
:d
Hai*_*der 18
谢谢大家,但问题不在于403代码.实际上问题在于我试图返回403的方式.我只是改变了我的代码HttpException而不是返回HttpStatusCodeResult并且现在每件事都有效.我可以通过抛出HttpException异常来返回任何HTTP状态代码,我的customErrors配置会捕获所有这些代码.可能HttpStatusCodeResult是没有做我期望它做的确切工作.
我刚换了
context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
Run Code Online (Sandbox Code Playgroud)
同
throw new HttpException((int)System.Net.HttpStatusCode.Forbidden, "Forbidden");
Run Code Online (Sandbox Code Playgroud)
而已.
快乐的编码.
Dus*_*ush 15
我也有这个问题.在OP的问题守则除了在自定义错误代码工作完美<system.web>节在web.config文件中.要解决这个问题我需要做的是添加以下代码<system.webServer>.请注意,‘webserver’而不是‘web’.
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="403" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/UnAuthorized" />
</httpErrors>
Run Code Online (Sandbox Code Playgroud)
如果有人使用以下环境,这是完整的解决方案:
环境:
自定义属性类:
将以下类添加到Web站点的默认命名空间.在接受的答案中解释的原因Stack Overflow问题: 为什么AuthorizeAttribute重定向到登录页面以进行身份验证和授权失败?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在web.config文件中添加以下代码
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="403" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/UnAuthorized" />
</httpErrors>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
下面的文章更多地解释了这一点:ASP.NET MVC:改进授权属性(403禁止)
而在web.config中httpErrors本文部分:揭秘ASP.NET MVC 5个错误页面和错误日志
然后将ErrorController.cs添加到Controllers文件夹
public class ErrorController : Controller
{
// GET: UnAuthorized
public ActionResult UnAuthorized()
{
return View();
}
public ActionResult Error()
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
然后将UnAuthorized.cshtml添加到View/Shared文件夹
@{
ViewBag.Title = "Your Request Unauthorized !"; //Customise as required
}
<h2>@ViewBag.Title.</h2>
Run Code Online (Sandbox Code Playgroud)
这将显示自定义错误页面而不是浏览器生成的错误页面.
另请注意,对于上述环境,不需要RegisterGlobalFilters按照其中一个答案中的建议对模板添加的方法内的代码进行注释.
请注意,我只是剪切并粘贴了我工作项目中的代码,因此我在上面的代码中使用了UnauthorizedOP NoPermissions.
这些似乎是复杂的解决方法。基本上,您需要执行以下操作才能使自定义错误页面 (CEP) 正常工作:
[HandleError]。ActionResult方法。<system.web>添加<customError mode="On" defaultRedirect="~/Error/Error">. 任何statusCode您没有 CEP 的问题都将由defaultRedirect.<error statusCode="[StatusCode]" redirect="~/Error/[CEP Name]">。您可以省略文件扩展名。控制器示例:
namespace NAMESPACE_Name.Controllers
{
[HandleError]
public class ErrorController : Controller
{
// GET: Error
public ActionResult BadRequest()
{
return View();
}
public ActionResult Error()
{
return View();
}
public ActionResult Forbidden()
{
return View();
}
public ActionResult InternalServerError()
{
return View();
}
public ActionResult NotFound()
{
return View();
}
public ActionResult NotImplemented()
{
return View();
}
public ActionResult ServerBusyOrDown()
{
return View();
}
public ActionResult ServerUnavailable()
{
return View();
}
public ActionResult Timeout()
{
return View();
}
public ActionResult Unauthorized()
{
return View();
}
}
}
Run Code Online (Sandbox Code Playgroud)
查看示例:
@{
Layout = "~/Views/Shared/_FullWidthLayout.cshtml";
ViewBag.Title = "404 Error";
}
<div class="opensans margin-sides text-center">
<div class="text-center">
<h1 class="text-normal">Uh oh! Something went wrong!</h1>
<div class="img-container text-center">
<div class="centered">
<h1 class="bold">404 - Not Found</h1>
</div>
<img class="img text-center" src="~/Images/BackgroundImg.png" style="opacity: 0.15;" />
</div>
<p class="text-left">
This is usually the result of a broken link, a web page that has been moved or deleted, or a mistyped URL.
<ol class="text-left">
<li>Check the URL you entered in the address bar for typos,</li>
<li>If the address you entered is correct, the problem is on our end.</li>
<li>Please check back later as the resource you requested could be getting worked on,</li>
<li>However, if this continues for the resource you requested, please submit a <a href="mailto:EmailAddress?subject=Website%20Error">trouble ticket</a>.</li>
</ol>
</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Web.Config 示例:
<customErrors mode="On" defaultRedirect="~/Error/Error">
<!--The defaultRedirect page will display for any error not listed below.-->
<error statusCode="400" redirect="~/Error/BadRequest"/>
<error statusCode="401" redirect="~/Error/Unauthorized"/>
<error statusCode="403" redirect="~/Error/Forbidden"/>
<error statusCode="404" redirect="~/Error/NotFound"/>
<error statusCode="408" redirect="~/Error/Timeout"/>
<error statusCode="500" redirect="~/Error/InternalServerError"/>
<error statusCode="501" redirect="~/Error/NotImplemented"/>
<error statusCode="502" redirect="~/Error/ServerUnavailable"/>
<error statusCode="503" redirect="~/Error/ServerBusyOrDown"/>
</customErrors>
Run Code Online (Sandbox Code Playgroud)
就是这样!一步步解决一个本来不应该是问题的问题!同样,任何statusCode您没有 CEP 的内容都将由该defaultRedirect页面处理。
| 归档时间: |
|
| 查看次数: |
52480 次 |
| 最近记录: |