Search code examples
asp.netcontrollerattributeshttp-headersdecorator

Replace Response.Headers.Add with method attribute decorator


In a Controller, I have this method:

public async Task<IActionResult> DownloadReportAsync()
{
    var file = GetFile();
    Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
    return File(Encoding.UTF8.GetBytes(file), "text/csv", "fileName");
}

Is there a way to replace the line Response.Headers.Add() with an attribute decorator on the method like [ResponseHeader("Access-Control-Expose-Headers", "Content-Disposition")] to have a more clean code? I don't want middleware to apply to all requests. Just to some methods.

Tries:

  1. I have found some document Filters in ASP.NET Core but when I paste the attribute [ResponseHeader(..)], it is unrecognized and no 'using' can be imported.
  2. If I can create a custom attribute for a method. I would consider that a very nice solution.

Solution

  • Managed to do it using .NET Filters

    Filters/ResponseHeaderAttribute.cs

    public class ResponseHeaderAttribute : ActionFilterAttribute
    {
        private readonly string _name;
        private readonly string _value;
    
        public ResponseHeaderAttribute(string name, string value) => (_name, _value) = (name, value);
    
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            context.HttpContext.Response.Headers.Add(_name, _value);
    
            base.OnResultExecuting(context);
        }
    }
    

    Controller.cs

    [ResponseHeader("Access-Control-Expose-Headers", "Content-Disposition")]
    public ActionResult Method() {}