所以我基本上有这样的签名:
[HttpGet, Route("widget/{widgetId}"), ResponseType(typeof(Widget))]
public async Task<IActionResult> GetWidgetWithValues([FromQuery] DashboardFilters filters, int widgetId = 1024)
像这样的DashboardFilters POCO:
public class DashboardFilters
{
[DefaultValue("6/1/2019")]
public DateTime Start { get; set; }
public DateTime End { get; set; }
public IEnumerable<int> UniversityIds { get; set; }
[SwaggerDefaultValue("Test", "Hello there")]
public string Test { get; set; }
}
我尝试设置'DefaultValue'和'SwaggerDefaultValueAttribute'
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
internal class SwaggerDefaultValueAttribute : Attribute
{
public SwaggerDefaultValueAttribute(string parameterName, object value) => (this.ParameterName, this.Value) = (parameterName, value);
public string ParameterName { get; private set; }
public object Value { get; set; }
}
基本上没有任何作用。我仍然可以使用此命令轻松设置标头参数:
public class SwaggerAddAuthHeader : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
Description = "JWT",
In = "header",
Type = "string",
Default = "Bearer "
});
}
}
将其连接起来,像这样:
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new Info { Title = $"Admin API", Version = "v1", Description = $"Last updated: {settings.General.DateUpdated}" });
//This enables the /// comments on each method to be used better for swagger
x.IncludeXmlComments(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".xml"));
x.OperationFilter<SwaggerAddAuthHeader>();
});
我试图在SwaggerAddAuthHeader中为'BodyParameter'添加一些内容,并且'default'属性消失了。有人碰到这个吗?似乎很奇怪,您没有办法为复杂类型定义默认值。是的,我知道使用简单的原语就可以像上面一样生成它们的默认值。