问题
I have controller method with ObjectId
params:
[ProducesResponseType(200, Type = typeof(Test))]
[HttpGet]
[Route("{id}")]
public IActionResult Get(ObjectId id)
{...
For this API method swagger generates a form with both of complex ObjectId model and string Id instead of single string param: How I can remove extra fields and keep only string Id?
回答1:
Find out what answer from another story also adresses this issue:
services.AddMvc(options =>
{
...
options.ModelMetadataDetailsProviders.Add(
new BindingSourceMetadataProvider(typeof(ObjectId), BindingSource.Special));
});
回答2:
It is possible to filter output fields for swagger form generator:
public class SwaggerOperationFilter : IOperationFilter
{
private readonly IEnumerable<string> objectIdIgnoreParameters = new[]
{
nameof(ObjectId.Timestamp),
nameof(ObjectId.Machine),
nameof(ObjectId.Pid),
nameof(ObjectId.Increment),
nameof(ObjectId.CreationTime)
};
public void Apply(Operation operation, OperationFilterContext context)
{
operation.Parameters = operation.Parameters.Where(x =>
x.In != "query" || objectIdIgnoreParameters.Contains(x.Name) == false
).ToList();
}
}
and use this filter in Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSwaggerGen(options =>
{
...
options.OperationFilter<SwaggerOperationFilter>();
});
...
As the result, we have only Id field:
来源:https://stackoverflow.com/questions/59800064/swagger-swashbuckle-for-c-shows-mongo-objectid-as-several-fields-instead-of-s