[我使用Swashbucket和Swashbucket.Examples NugetPackages在.NET Framework(v.4.7.2)中提供Swagger API]
按照文档在https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters我试图像这样使用SwaggerRequestExample属性:
[HttpPost]
[Route("search")]
[SwaggerRequestExample(typeof(OrderRequestExample), typeof(OrderRequestExampleProvider))]
public async Task<HttpResponseMessage> SearchAsync()
{
...
}
我的启动类的配置如文档中所述:
config.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "MyApi");
c.OperationFilter<ExamplesOperationFilter>();
c.IncludeXmlComments(System.String.Format(@"{0}\bin\MyApi_Api.xml",
System.AppDomain.CurrentDomain.BaseDirectory));
//c.OperationFilter<AddResponseHeadersFilter>();
}).EnableSwaggerUi(c => { c.DocumentTitle("My API");});
[当我使用SwaggerRequestExample属性时,UI显示错误:
500 : {"Message":"An error has occurred.","ExceptionMessage":"Der Wert darf nicht NULL sein.\r\nParametername: source","ExceptionType":"System.ArgumentNullException","StackTrace":" bei System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)\r\n bei Swashbuckle.Examples.ExamplesOperationFilter.SetRequestModelExamples(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)\r\n bei Swashbuckle.Examples.ExamplesOperationFilter.Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)\r\n bei Swashbuckle.Swagger.SwaggerGenerator.CreateOperation(ApiDescription apiDesc, SchemaRegistry schemaRegistry)\r\n bei Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable`1 apiDescriptions, SchemaRegistry schemaRegistry)\r\n bei Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass7.<GetSwagger>b__4(IGrouping`2 group)\r\n bei System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)\r\n bei Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)\r\n bei Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n bei System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n bei System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n bei System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n bei System.Web.Http.HttpServer.<SendAsync>d__24.MoveNext()"} https://localhost:44384/swagger/docs/v1
显然,缺少“源”(IEnumerable)(为空)。我找不到添加它的位置。
示例类:
public class OrderRequestExampleProvider : IExamplesProvider
{
public object GetExamples()
{
return new OrderRequestExample()
{
Name = "some name"
};
}
}
public class OrderRequestExample
{
public string Name { get; set; }
}
解决方案似乎很明显,但是如果您在方法签名中不使用主体的反序列化,则会出现此错误。