返回自定义错误

我设计了一个名为ErrorController的Controller,其方法有ForbiddenNotFound ,所以我可以在Web.config中添加以下几行:

     

所以现在我希望能够做到这样的事情:

 public ActionResult Edit(int idObject) { if( user.OnwsObject(idObject) ) { // lets edit } else { // ** SEND AN ERROR 403 *** // And let ASP.NET MVC with IIS manage that error to send // the requester to the Web.config defined error page. } } 

问题是我尝试过这样的事情:(A) throw new HttpException(403, "Error description"); :导致Unhandledexception导致系统崩溃,(B) return HttpStatusResultCode(403, "Error description") :导致这些错误的系统默认页面。

我该怎么用?

提前致谢。

实际上你不能使用web.config进行403重定向。

您可以做的是覆盖控制器上的OnActionExecuted以检查状态代码并重定向到web.config中定义的任何内容,如下所示

Web.config文件:

    

你的HomeController

 public class HomeController : Controller { protected override void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext.HttpContext.Response.StatusCode == 403) { var config = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors"); string urlToRedirectTo = config.Errors["403"].Redirect; filterContext.Result = Redirect(urlToRedirectTo); } base.OnActionExecuted(filterContext); } public ActionResult Edit(int idObject) { if(!user.OnwsObject(idObject)) { Response.StatusCode = 403; } return View(); } } 

ErrorController:

 public class ErrorController : Controller { public ActionResult Forbidden() { Response.StatusCode = 403; return View(); } } 

更通用的解决方案是创建一个可以应用于控制器或单个操作的动作filter:

 public class HandleForbiddenRedirect : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext.HttpContext.Response.StatusCode == 403) { var config = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors"); string urlToRedirectTo = config.Errors["403"].Redirect; filterContext.Result = new RedirectResult(urlToRedirectTo); } base.OnActionExecuted(filterContext); } } 

现在,您可以将操作filter应用于控制器,以便在403上重定向所有操作

 [HandleForbiddenRedirect] public class HomeController : Controller { //... } 

或者在403上有一个单独的动作重定向

 public class HomeController : Controller { [HandleForbiddenRedirect] public ActionResult Edit(int idObject) { //... } } 

或者,如果您不想装饰所有控制器和操作但想要在任何地方应用它,您可以将它添加到Global.asax的Application_Start中的filter集合中

 GlobalFilters.Filters.Add(new HandleForbiddenRedirect()); 

看到这篇文章这应该可以解决你的问题。

如何使自定义错误页在ASP.NET MVC 4中工作

基本上你需要用viewresult OR创建控制器

ASP.NET MVC HandleError