Pete rudensky
Pete rudensky

Reputation: 484

How can I add a header in OnResultExecuted

I need to add a header to the response.

The header value is based on the response body.

When I try to add the header I get an error: 'Headers are read-only, response has already started.'

public class SecurityFilter : ActionFilterAttribute
{
    public override async void OnActionExecuting(ActionExecutingContext context)
    {
        var body = await new StreamReader(context.HttpContext.Request.Body).ReadToEndAsync();
    }

    public override void OnResultExecuted(ResultExecutedContext context)
    {
        var objectResult = context.Result as ObjectResult;
        var resultValue = objectResult.Value;
        Console.WriteLine(resultValue);

        context.HttpContext.Response.Headers.Add("foo", "bar");

        base.OnResultExecuted(context);
    }
}

Upvotes: 2

Views: 963

Answers (1)

Rena
Rena

Reputation: 36715

OnResultExecuted method is called after the action result executes. Response headers can't be set/modified if the result has been done.

You can use OnActionExecuted method which is called after the action executes, before the action result. Or use OnResultExecuting method which is called before the action result executes.

Here is a simple demo you could follow:

public class SecurityFilter : ActionFilterAttribute
{
    public override async void OnActionExecuting(ActionExecutingContext context)
    {
    }
    public override void OnActionExecuted(ActionExecutedContext context)
    {           
        var objectResult = context.Result as ObjectResult;
        var resultValue = objectResult.Value;
        Console.WriteLine(resultValue);
        context.HttpContext.Response.Headers.Add("foo", "bar");
        base.OnActionExecuted(context);
    }        
}

Upvotes: 1

Related Questions