Redirect Detection in IActionFilter.OnAction Completed Reliably

I have IActionFilterone that does something in OnActionExecuted, however I don’t want to perform this action when the result of the controller is redirecting.

My initial thought was to check the type ActionResultas on RedirectResultor RedirectToRouteResult, but this is unreliable, since any type of result can do the redirection (indeed, I have two custom ones that do).

Is there any other way to detect when this will happen, or is it impossible, since you won't know about the redirect until the action completes (which is too late to do what I want)?

Perhaps just checking on ViewResultand PartialViewResultwill be more reliable.

+3
source share
2 answers

... it's unreliable how any type of result can perform a redirect (indeed, I have two custom ones that do)

If they are redirecting, this must be done by setting the Result to RedirectResult or similar, not just Response.Redirect.
If this is Response.Redirect, then this is simply wrong.
Example: AuthorizeAttribute, which changes the result to HttpUnauthorizedResult.

That way, you still get ControllerContext.Result and you can work with it.


Also, what about applying the convention: if the type name ActionResult contains the word "redirection" than redirection.

var isRedirect = filterContext.ActionResult.GetType().Name.Contains("Redirect");

, , , , .

, , .

+2

. "[IsRedirect]", "... " "IRedirectResult" .

, :

  • OnResultExecuted , HTTP (URL ..) - ,
  • Result.Execute() , . , - "".

.

0

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