Ulana
Ulana

Reputation: 383

Add header to response base on status code

I'm trying to add a headers to response base on status code. I used a ActionFilterAttribute, but OnResultExecuting method always return the status OK, becasue response didnt start yet. And I could not add a header to OnResultExecuted because we culd not modify response. Any idea where i can add a header?

public override void OnResultExecuting(ResultExecutingContext context)
    {
        var httpContext = context.HttpContext;

        if (context.HttpContext.Response.StatusCode == Microsoft.AspNetCore.Http.StatusCodes.Status200OK)  // doesnt work since it is always 200
        {
            httpContext.Response.Headers.Add("flag1", "false");

Upvotes: 1

Views: 2617

Answers (2)

Xueli Chen
Xueli Chen

Reputation: 12725

If your returned result is a StatusCodeResult, you could may try the below :

 public override void OnResultExecuting(ResultExecutingContext context)
 {
        var httpContext = context.HttpContext;

        if (context.Result is StatusCodeResult statusCodeResult &&
        statusCodeResult.StatusCode == 200)
        {
            httpContext.Response.Headers.Add("flag1", "false");
        }
  }

Upvotes: 1

Ismail Umar
Ismail Umar

Reputation: 1124

I will say you consider using a Middleware and do something like this

app.UseExceptionHandler(appBuilder =>
                {
                     appBuilder.Run(async context =>
                     {
                          var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
                          if (exceptionHandlerFeature != null)
                          {
                               var logger = loggerFactory.CreateLogger("Global exception logger");
                               logger.LogError(500,
                                   exceptionHandlerFeature.Error,
                                   exceptionHandlerFeature.Error.Message);
                          }
                          context.Response.StatusCode = 500;
                          await context.Response.WriteAsync("An unexpected fault happened. Try again later.").ConfigureAwait(false);
                     });
                });

See if something like this works for your case. I hope this helps

Upvotes: 0

Related Questions