Using of HandleErrorAttribute in ASP.NET MVC appli

2020-07-06 03:25发布

问题:

I have a question about the best way of using HandleErrorAttribute in my MVC 5 application. As we know, we can add this attribute to global filters like that:

 filters.Add(new HandleErrorAttribute{View = "Error"});

This involves the app to show the 'Error' view every time when an unhandled exception is thrown in any level of app. But, if I have some logic in another global authorize or action filter, that produces some exception, then when the exception is thrown for first time, the app tries to redirect to the Error View, again other filters begin executing and produce the same exception again, so asp.net to avoid looping terminates the app. So what is the best way to use this HandleErrorAttribute to avoid such behavior? Thanks!

Edit: After some debugging I found that this is not the usual behavior of HandleErrorAttribute, so looping happens for me only when I use custom Routes f.e.

{key}/{controller}/{action}

and when some error occurs in the filter logic, then the app tries to redirect to the Error View, but again another filter logic begins to exectue and I even see an "Error" value in the {key} route parameter, so it is unwanted behavior. When I use the default route {controller}/{action} this doesn't happen and I get exactly to the Error View without executing any global filter logic a second time.

回答1:

You should wrap your action filter logic inside a try catch, then inside the catch block, redirect to the Error view and pass the Exception.

Your only other alternative is to ditch HandleError completely and use the Application_Error event inside Global.asax to manage your error handling. That way you can redirect to your Error action inside there regardless of where the error occured.



回答2:

Matt is right about global.asax... this is the example I followed http://www.digitallycreated.net/Blog/57/getting-the-correct-http-status-codes-out-of-asp.net-custom-error-pages

Then in each view I added: Response.StatusCode = 500; or which ever other code I wanted to show back to the client.