根据标题 – 我已经找到了如何使用常规.NET执行此操作的示例
例如:
Web Api How to add a Header parameter for all API in Swagger
但是,我找不到任何示例或文档,说明如何在使用.NET Core 2.0时完成相同的操作.
解决方法
swagger / OpenApi请求标头和响应标头中有两种类型的标头.
请求标题
请求标头很容易实现,您需要做的就是装饰您的控制器和/或操作,如下所示:
[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 it to the swagger document.
响应标题
在Asp.Net Core或Swashbuckle中没有指定响应头的声明方式,因此您必须手动执行此操作.
[Route("api/[controller]")] public class ResponseHeadersController : Controller { [HttpGet] public string Get() { HttpContext.Response.Headers["x-my-header"] = "header value"; return "value"; } }
我们现在需要指示swagger包含响应头.这是通过IOperationFilter完成的,请参阅Swashbuckle documentation了解过滤器的工作原理.可以全局或按操作应用过滤器,但是您无法通过将参数传递到其构造函数来自定义行为,而是按照声明过滤器的方式(仅按类型).
因此,您必须为每个返回一个或多个响应标头的API方法编写一个操作过滤器.或者,您可以定义一个属性来声明操作的响应头.
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; } }
这使我们能够为每个响应代码声明一个或多个标头.
[HttpGet] [ProducesResponseHeader("x-my-header",(int)HttpStatusCode.OK)] public string Get() { HttpContext.Response.Headers["x-my-header"] = "header value"; return "string"; }
现在我们有一个定义我们意图的属性,我们可以创建一个通用的操作过滤器.
public class ResponseHeadersFilter : IOperationFilter { public void Apply(Operation operation,OperationFilterContext context) { // Get all response header declarations for a given operation var actionResponsesWithHeaders = context.ApiDescription.ActionAttributes() .OfType<ProducesResponseHeaderAttribute>() .ToArray(); if (!actionResponsesWithHeaders.Any()) return; foreach (var responseCode in operation.Responses.Keys) { // Do we have one or more headers for the specific response code var responseHeaders = actionResponsesWithHeaders.Where(resp => resp.StatusCode.ToString() == responseCode); if (!responseHeaders.Any()) continue; var response = operation.Responses[responseCode]; if (response.Headers == null) response.Headers = new Dictionary<string,Header>(); foreach (var responseHeader in responseHeaders) { response.Headers[responseHeader.Name] = new Header { Type = responseHeader.Type.ToString(),Description = responseHeader.Description }; } } } }
我们现在需要做的就是将操作过滤器连接到swagger生成.
// Startup.cs services.AddSwaggerGen(c => { ... c.OperationFilter<ResponseHeadersFilter>(); };
我希望这足以让你前进.