Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc custom exception filter to force a return of full view, not partial

I have a custom exception filter that I'm calling by virtue of adding a [CustomExceptionFilter] attribute to my class. It works as I'd like it to, however if the action method is returning a partial view (through an ajax request), the exception (which is basically a redirect to a not authorized page), is loading up the partial view with that page. Is there a way I can force it to reload the 'parent' url?

Here is the code for the custom exception filter

public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception.GetType() == typeof(CustomSecurityException))
        {
            filterContext.ExceptionHandled = true;
            RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
            string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "NoAccess", action = "Index", message = filterContext.Exception.Message })).VirtualPath;
            filterContext.HttpContext.Response.Redirect(url, true);
        }
    }
}
like image 497
Kyle Avatar asked Feb 12 '10 16:02

Kyle


People also ask

How do I create a custom exception filter?

Right-click on create method and add view. Add the CustomExceptionHandlerFilter class for creating a custom exception handler. Implements FilterAttribute and IExceptionFilter and overrides the OnException method. Open App_Start folder inside the App_start folder contains FilterConfig class.

Is try catch block really needed in MVC application when we have exception filters in MVC?

We have try catch block for error handling, But in case of MVC we have exception filters. In such case we can handle errors at filter level. i.e. by using exception filters.


1 Answers

This is something you need to handle on the browser. Try handling the error() on jQuery.ajax() call for example (and obviously don't return redirect..).

like image 176
ziya Avatar answered Oct 16 '22 06:10

ziya