How would you implement a filter that modifies the action's result based on the outcome, such as wrapping every successful response in a standard envelope?
Short answer
An IActionFilter/IAsyncActionFilter can inspect and replace context.Result after calling next() (in the 'after' phase), letting you transform whatever the action returned into a standardized shape -- like wrapping successful responses in a consistent envelope with metadata…
Advertisement
AModel answer
An IActionFilter/IAsyncActionFilter can inspect and replace context.Result after calling next() (in the 'after' phase), letting you transform whatever the action returned into a standardized shape -- like wrapping successful responses in a consistent envelope with metadata (timestamp, request ID) -- applied globally so every endpoint automatically gets consistent response formatting without each action needing to construct the envelope itself.
public class ResponseEnvelopeFilter : IAsyncActionFilter {
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
var executed = await next();
if (executed.Result is ObjectResult objResult && objResult.StatusCode is null or >= 200 and < 300) {
executed.Result = new ObjectResult(new {
data = objResult.Value,
timestamp = DateTime.UtcNow,
requestId = context.HttpContext.TraceIdentifier
});
}
}
}Real-world example
An API wraps every successful response in a standard envelope (with data, timestamp, and requestId fields) using a single global action filter, ensuring consistent response formatting across dozens of controllers without each action manually constructing the wrapper.
Likely follow-ups
- How would you exclude specific actions from this global wrapping behavior?
- What's the risk of a global filter like this interacting unexpectedly with error responses?
Related topics