Redirect To Action not carrying exception data

2019-06-13 01:51发布

问题:

I have a base controller which takes care of excption handling . so all my actions in the controller simply delegate to the action in basecontroller.

 catch (Exception ex)
            {
                return RedirectToAction("Error", ex);
            }

my base controller action is

   public ActionResult Error(Exception ex)

Teh problem here is excpetion details are getting clreared in Error Action in base controller. I think these are getting cleared during redirection.

回答1:

Yes, that's correct, when you do a redirect you're basically sending a 302 to the browser so the data is lost.

A possible way to temporarily save the data is saving it in the tempdata:

TempData["error"] = ex;

After that you can retrieve it in the Error-method:

Exception ex = TempData["error"] as Exception;

Note: the tempdata is for short-lived data and can be especially handy in redirect-scenarios



回答2:

In MVC 3 and higher exceptions caused inside the MVC pipeline had be handled, and include exception data, by using an HandleErrorAttribute and Error Views.

You would register the filer like so

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new HandleErrorAttribute());
}

And use a view similar to the following

@model System.Web.Mvc.HandleErrorInfo        
@ViewBag.Title = "Error"; 

<h2>An Error Has Occurred</h2> 

@if (Model != null) { 
      <p>
           @Model.Exception.GetType().Name<br /> 
           thrown in @Model.ControllerName @Model.ActionName
      </p> 
}

For a more detailed introduction see these articles:

http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html

http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/01/error-handling-and-customerrors-and-mvc3-oh-my.aspx