返回自定义错误 [英] Returning custom errors

查看:134
本文介绍了返回自定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设计了一个名为 ErrorController 控制器,如禁止 NOTFOUND ,所以我可以添加到Web.config中的以下行:

I have designed a Controller called ErrorController with methods like Forbidden or NotFound, so I could add to Web.config the following lines:

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

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

So now I want to be able to do something like that:

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)抛出新的HttpException(403,错误描述); :导致未处理的异常引起的系统崩溃,(B)返回HttpStatusResult code(403,错误描述):造成这些错误的系统默认页面

The problem is that I have tried things like: (A)throw new HttpException(403, "Error description");: resulting in an Unhandled exception that causes the system to crash, (B)return HttpStatusResultCode(403, "Error description"): resulting in a system default page for those errors.

我应该用什么呢?

先谢谢了。

推荐答案

其实你不能使用的web.config的403重定向。

Actually you can not use web.config for 403 redirects.

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

What you can do is override OnActionExecuted on a controller to check for the status code and redirect to whatever is defined in web.config, like this

Web.config文件:

Web.config:

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

您的HomeController

Your 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:

ErrorController:

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

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

More generic solution would be to create an action filter that you can apply to the controller or the individual action:

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重定向

Now you can apply the action filter to the controller so that all actions redirect on 403

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

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

Or have an individual action redirect on 403

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

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

Or if you don't wont to decorate all the controllers and action but want to apply it everywhere you can add it in filter collection in Application_Start of Global.asax

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

这篇关于返回自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆