How to abort / intercept MVC actions with ActionFilters?

Remember to close this if it is a duplicate. I could not find the answer.

I want to place System.Web.ActionFilterAttribute in an action method and override the OnActionExecuting method to insert business logic that determines whether the action should be performed.

Can I use an ActionExecutingContext to cancel an executable action method and do one of the following:

  • Send the HTTP status code (and the corresponding <customError> page).
  • Perform a different action method within the same controller.
+4
source share
2 answers

Send the HTTP status code (and the corresponding <customError> page)

Nearly:

 public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Response.StatusCode = 500; } 

Perform a different action method within the same controller.

Yes:

 public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Result = new ViewResult() { ViewName = "SomeOtherAction" }; } 
+2
source

You can always redirect to another controller / action in the action filter.

See here for an example.

+1
source

Source: https://habr.com/ru/post/1314482/


All Articles