C#学习教程:将查询字符串参数添加到我的Swagger规范我有几个返回列表的GET端点,我允许用户在QueryString示例中添加每页和页面参数:http://myapi.com/endpoint/?page=5&pagepage=10我看到swagger确实支持“查询”中的参数,但我如何让Swashbuckle做到这一点?我在其中一条评论中提到,我通过创建一个自定义属性来解决我的问题,让我可以做我需要的事情。这是我的解决方案的代码:[AttributeUsage(AttributeTargets.Method,Inherited=false,AllowMultiple=true)]描述=描述;}公共字符串名称{得到;私有集;}publicTypeDataType{get;放;}publicstringParameterType{get;放;}公共字符串描述{得到;私有集;}publicboolRequired{get;放;}=假;}使用Swagger配置注册属性:GlobalConfiguration.Configuration.EnableSwagger(c=>{c.OperationFilter();});然后将此属性添加到您的方法中:[SwaggerParameter("page","Pagenumbertodisplay",DataType=typeof(Int32),ParameterType=ParameterType.inQuery)][SwaggerParameter("perpage","Itemstodisplayperpage",DataType=typeof(Int32),ParameterType=ParameterType.inQuery)]你可以轻松实现这一点。假设您有一个ItemsController,其操作如下:[Route("/api/items/{id}")]publicIHttpActionResultGet(intid,int?page=null,int?perpage=null){//一些相关的代码返回OK();}Swashbuckle将生成此规范(仅显示相关部分):"paths":{"/api/items/{id}":{"get":{"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"page","in":"query","required":false,"type":"integer","format":"int32"},{"name":"limit","in":"query","required":false,"type":"integer","format":"int32"}]}}如果你想要page和perpage,只需使参数不可为null。以下是有关SwaggerParametersAttributeHandler缺少信息的一些注释。它是一个操作过滤器,可帮助您确定如何对属性执行操作。下面是我使用的示例处理程序,它允许我使用SwaggerParameterAttribute覆盖可为null的参数的必填字段。以上就是C#学习教程:为我的Swagger规范添加查询字符串参数分享全部内容。如果对大家有用,需要详细了解C#学习教程,希望大家多加关注——publicclassRequiredParameterOverrideOperationFilter:IOperationFilter{publicvoidApply(Operationoperation,SchemaRegistryschemaRegistry,ApiDescriptionapiDescription){//获取所有SwaggerParameterAttributes在方法上varattributes=apiDescription.ActionDescriptor.GetCustomAttributes();if(operation.parameters==null){operation.parameters=newList();}//对于找到的每个属性,找到操作参数(这是Swagger寻找生成Swagger文档的地方)//根据每个属性的必填字段覆盖必填字段(属性中的var属性){varreferringOperationParameter=operation.parameters.FirstOrDefault(p=>p.name==attribute.Name);if(referencingOperationParameter!=null){referencingOperationParameter.required=attribute.Required;}}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
