我将Swagger / Swashbuckle集成到了.NET Core 2.2 API项目中。一切都很好,我要问的纯粹是为了方便。考虑以下API方法:
I have Swagger/Swashbuckle integrated into a .NET Core 2.2 API project. Everything works great and what I am asking is purely for convenience. Consider the following API method:
public Model SomeEstimate(SomeRequest request) { return Manager.GetSomeEstimate(request); } ... public class SomeRequest { public string StreetAddress { get; set; } public string Zip { get; set; } }当我打/swagger/index.html并想尝试一下时API,我总是必须输入StreetAddress和Zip值。
When I hit /swagger/index.html and want to try out this API, I always have to enter the StreetAddress and Zip values.
是否可以提供StreetAddress和Zip的默认值?此答案建议放置[DefaultValue(此处的值)]属性的 SomeRequest 类。它可能适用于常规.NET,但不适用于.NET Core。
Is there a way to provide default values for StreetAddress and Zip? This answer suggested placing [DefaultValue("value here")] attribute each property of the SomeRequest class. It may have worked for the regular .NET, but not with .NET Core.
是否可以为Swagger UI提供参数的默认值?
Is it possible to provide default values for parameters for the Swagger UI?
推荐答案要为.NET Core中的Swagger UI定义参数的默认值,请使用以下文章为Model类中的DefaultValue属性定义了一个自定义模式过滤器。下面显示的代码摘自本文,纯粹是为了告知其他任何有此问题或面临类似问题的人:
To define default values for parameters for Swagger UI in .NET Core, the following article defines a custom schema filter for your DefaultValue attribute in your Model class. The code shown below has been taken from this article and is purely to inform anyone else who has this question or has been facing a similar problem:
在模型:
public class Test { [DefaultValue("Hello")] public string Text { get; set; } }主过滤器:
using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; namespace Project.Swashbuckle { public class SchemaFilter : ISchemaFilter { public void Apply(Schema schema, SchemaFilterContext context) { if (schema.Properties == null) { return; } foreach (PropertyInfo propertyInfo in context.SystemType.GetProperties()) { // Look for class attributes that have been decorated with "[DefaultAttribute(...)]". DefaultValueAttribute defaultAttribute = propertyInfo .GetCustomAttribute<DefaultValueAttribute>(); if (defaultAttribute != null) { foreach (KeyValuePair<string, Schema> property in schema.Properties) { // Only assign default value to the proper element. if (ToCamelCase(propertyInfo.Name) == property.Key) { property.Value.Example = defaultAttribute.Value; break; } } } } } private string ToCamelCase(string name) { return char.ToLowerInvariant(name[0]) + name.Substring(1); } } }最后将其注册到您的Swagger选项(在Startup.cs中):
And finally registering it to your Swagger Options(In Startup.cs):
services.AddSwaggerGen(c => { // ... c.SchemaFilter<SchemaFilter>(); });更多推荐
如何为Swagger UI定义参数的默认值?
发布评论