There are two types of headers in swagger / OpenApi request headers and response headers.
Request header
Request headers are easy to implement, all you have to do is decorate your controller and / or operation as follows:
[Route("api/[controller]")] public class RequestHeadersController : Controller { [FromHeader(Name = "x-my-controller-wide-header")] public string MyControllerWideHeader { get; set; } [HttpGet] public string Get([FromHeader(Name = "x-my-operation-header")]string myOperationHeader) { return myOperationHeader; } }
Swashbuckle.AspNetCore will automatically pick up any headers defined with FromHeaderAttribute and apply them to the swagger document.
Answer Headers
There is no declarative way to specify response headers in Asp.Net Core or Swashbuckle, so you have to do it manually.
The following is an example x-my-header custom header name.
[Route("api/[controller]")] public class ResponseHeadersController : Controller { [HttpGet] public string Get() { HttpContext.Response.Headers["x-my-header"] = "header value"; return "value"; } }
Now we need to instruct the swagger to include the response header. This is done through an IOperationFilter, see the Swashbuckle documentation on how filters work. Filters can be applied globally or for each operation, but you cannot configure the behavior by passing parameters to its constructor; do as filters are declared (only by type). As a result, you will have to write an operation filter for each API method that returns one or more response headers. Alternatively, you can define an attribute to declare response headers for the operation.
public enum HeaderResponseType { String, Number } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class ProducesResponseHeaderAttribute : Attribute { public ProducesResponseHeaderAttribute(string name, int statusCode) { Name = name ?? throw new ArgumentNullException(nameof(name)); StatusCode = statusCode; Type = HeaderResponseType.String; } public string Name { get; set; } public int StatusCode { get; set; } public HeaderResponseType Type { get; set; } public string Description { get; set; } }
This enables us to declare one or more headers for each response code.
[HttpGet] [ProducesResponseHeader("x-my-header", (int)HttpStatusCode.OK)] public string Get() { HttpContext.Response.Headers["x-my-header"] = "header value"; return "string"; }
Now that we have an attribute that defines our intent, we can create a common filter of work.
public class ResponseHeadersFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) {
All we need to do is connect a working filter to the swagger generation.
Hope this is enough to get you started.