Child Action Exception Handler

1k Views Asked by At

I have a simple Controller:

public class RedirectController : Controller {
    public ActionResult Index() {
        return View();
    }

    [ChildActionOnly]
    public ActionResult Child1() {
        return View();
    }


    [ChildActionOnly]
    public ActionResult Child2() {
        return View();
    }

[ChildActionOnly]
    public ActionResult Child3() {
        throw new Exception("abc");        
    }
}

Index.cshtml

...
@Html.Action("Child1")
...

Child1.cshtml

...
@Html.Action("Child2")
...

Child2.cshtml

...
@Html.Action("Child3")
...

Child3 will throw a exception throw new Exception("abc") For some reason, I set layout for error.cshtml , than finally export contents contains Index.cshtml , Child1.cshtml , Child2.cshtml and Error.cshtml

So I defined a custom ExceptionFilter to deal this exception

public class MyExceptionAttribute : ActionFilterAttribute , IExceptionFilter {

    public void OnException(ExceptionContext filterContext) {
    ...
        ...
        if(filterContext.ParentActionViewContext != null) {
    //remove parent actions' exported contents
            ViewContext par = filterContext.ParentActionViewContext;
            while(null != par){
                var wtr = (StringWriter)par.Writer;
                wtr.GetStringBuilder().Clear();
                par = par.ParentActionViewContext;
            }

        }
...
...

After do this filter, the finally output html removed "Index", "Child1" and "Child2" content, but "Layout" content still outputed.

<html>
    ...(Layout content)
    <html>
    ...(Error.cshtml content)
    </html>
</html>

Is there any way to remove all contents except error's content ?

1

There are 1 best solutions below

0
On

I have a solution:

When child action throw a exception, custom ExceptionFilter handled it, and remove all parent actions' output but layout.

So, in _ViewStart.cshtml:

@{
if(!this.ViewContext.IsChildAction) {
    Layout = "~/Views/Shared/_Layout.cshtml";
}
}