Asp.net mvc OnResultExecuting change filterContext Result

Simple question. How can I override the OnResultExecuting method in my controller and create another ActionResult instead?

The following is sample code. Currently, the original ActionResutl continues to execute, and my new RedirectResult is ignored.

RedirectResult redirectResult = new RedirectResult("http://www.google.com"); filterContext.Result = redirectResult; base.OnResultExecuting(filterContext); 
+6
asp.net-mvc
source share
4 answers

It would be possible if you override the OnActionExecuted method.

Example:

 protected override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.Result = new RedirectResult("http://google.com"); base.OnActionExecuted(filterContext); } 
+9
source share

I wanted to know the same thing. I searched google and came across your question plus others, and the answers were all the same. Use the IActionFilter.OnActionExecuted method.

However, this is actually not a question that is more related to the work, as with the @ randy-burden you can change / replace the result of the RedirectToRouteResult action as a result of the filter. So why not the result of RedirectRoute?

If you really want to redo a specific URL inside the IResultFilter.OnResultExecuting method, you can do one of the following:

 RedirectResult redirectResult = new RedirectResult("http://www.google.com"); filterContext.Result = redirectResult; filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext); filterContext.Cancel = true; base.OnResultExecuting(filterContext); 

or

 filterContext.HttpContext.Response.RedirectLocation = "http://www.google.com"; filterContext.HttpContext.Response.StatusCode = 302; filterContext.Cancel = true; base.OnResultExecuting(filterContext); 

In the first option, you manually execute RedirectResult and, by filterContext.Cancel = true , you tell the framework that you do not need to run filterContext.Result . In the second option, you essentially do the same, but instead of RedirectResult setting up the Http response, you do it yourself.

In my case, I wanted to add an additional request parameter to the redirect URL and tell the infrastructure where I wanted to cancel the result of the redirect action, and then the redirection seemed a little wrong anyway, but it really works.

+6
source share

I needed to redirect from OnActionExecuting and finished this and it worked:

  filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary {{"controller", "Base"}, {"action", "Error"}, {"errorMessage", errorMessage}}); 
+1
source share

You can just do it if using MVC5

 public void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Redirect("http://www.google.com"); } 
+1
source share

All Articles