2013-07-26 118 views
3

我设计了一个名为ErrorController与像ForbiddenNotFound方法控制器,所以我可以添加到Web.config中的以下行:所以现在返回自定义错误

<customErrors mode="On" defaultRedirect="~/Error/Unknown" /> 
    <error statusCode="404" redirect="~/Error/NotFound" /> 
    <error statusCode="403" redirect="~/Error/Forbidden" /> 
</customErrors> 

我希望能够像做即:

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");:导致未处理的异常,导致系统崩溃,(B)return HttpStatusResultCode(403, "Error description"):导致系统defau lt这些错误的页面。

应该改用什么?

在此先感谢。

+0

没有尝试添加Response.StatusCode = 403 ; ?然后返回Json作为错误描述的结果? – taffarel

+0

保持显示IIS默认页面而不是自定义:( –

回答

4

其实你不能使用的web.config为403个重定向创建控制器。

你可以做的是覆盖OnActionExecuted一个控制器上,以检查状态代码和重定向到无论是在web.config中定义,这样

Web.config文件:

<customErrors mode="On"> 
    <error statusCode="403" redirect="~/Error/Forbidden" /> 
</customErrors> 

你的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(); 
    } 
} 

更通用的解决方案是创建可以应用到控制器或个人动作一个动作过滤器:

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); 
    } 
} 

现在你可以将操作筛选到控制器,使所有的行动上403重定向

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

,或是有个人行为重定向403

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

或者,如果你不惯于装饰所有的控制器和行动,但想处处应用它,你可以在过滤器的Application_Start集合中添加它的Global.asax

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

让我今晚测试它,看起来很棒 –

相关问题