Reputation: 1697
I am developing a full-web application and I am using the ASP.NET MVC 3 framework. I am implementing a subclass of ActionFilterAttribute
.
I am overriding the OnActionExecuting
method. If an exception is caught in OnActionExecuting
method I want to redirect the client browser. The redirection URL targets an action method in one of my controllers. I want to pass data from the Exception
object into the redirection URL.
Is there a way to build a URL including the Exception
object and then passing the URL into the RedirectResult
constructor?
Upvotes: 5
Views: 6712
Reputation: 1001
You can use TempData for situations like this.
Just set TempData["MyException"] = myException
before you redirect and then check for that TempData value in the action you redirect to.
Upvotes: 3
Reputation: 1391
A better solution would be to use the [HandleError] attribute. What this attribute does is when an error occurs, the user will be presented with the Error view. The way it works is when an error is encountered, if the [HandleError] attribute is present, ASP.NET MVC will search for an Error view, first in the controller's view folder, then in the shared view folder.
For instance:
[HandleError]
public class FooController : Controller {
...
}
When an error occurs in any action for the FooController, ASP.NET MVC will first search in ~/Views/Foo for an Error view (a view named Error.aspx for the ASP.NET view engine, or Error.cshtml for the razor view engine). If that view is not found, it will search in ~/Views/Shared.
In your view you can display a generic error, as well as display any exception information.
See http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx for a more detailed explanation of the [HandleError] attribute.
Upvotes: 2
Reputation: 1038730
Is there a way to build a URL including the Exception object and then passing the URL into the RedirectResult constructor ?
No. You can pass only query string parameters like for example:
var values = new RouteValueDictionary(new
{
action = "foo",
controller = "bar",
exceptiontext = "foo bar baz"
});
filterContext.Result = new RedirectToRouteResult(values);
and in the target action you will be able to fetch the exception text parameter:
public Action Foo(string exceptionText)
{
...
}
Upvotes: 8