Can someone explain the difference between the Action Filter and the Result Filter in ASP.NET Core MVC? I really didn't get it reading the documentation. What exactly is the result execution that we see in the diagram here (gray box on the very bottom): 
In the documentation it says that
Action filters can change the result returned from the action.
So if it already changes the result why do we need an Result filter?
According to Microsoft Docs:
Action filters:
- Run code immediately before and after an action method is called.
- Can change the arguments passed into an action.
- Can change the result returned from the action.
- Are not supported in Razor Pages.
But, the ResultFilters have a bit difference in executaion:
Result filters run code immediately before and after the execution of action results. They run only when the action method has executed successfully. They are useful for logic that must surround view or formatter execution.
Consider you want to return an API response to the client for a User model with lots of properties. You can simply create a response based on the API model contract like this:
public class UserDetailFilter : ResultFilterAttribute
{
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
var result = context.Result as ObjectResult;
if (result?.Value is UserResponse value)
result.Value = new
{
Id = value.Id,
Username = value.Username,
Fullname = value.Fullname,
Mobile = value.Mobile,
Email = value.Email,
UpdatedAt = value.UpdatedAt
};
await next();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With