Skip to content

Commit fc77e5a

Browse files
authored
Allow no match to be found to avoid throwing an exception (#3188)
Allow no match to be found to avoid throwing an exception for raw content.
1 parent 3832d77 commit fc77e5a

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/SwaggerGenerator.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,7 @@ private async Task<OpenApiOperation> GenerateOpenApiOperationFromMetadataAsync(A
443443
}
444444
else
445445
{
446-
bodyParameterDescription = apiDescription.ParameterDescriptions.Single(desc => desc.IsFromBody());
446+
bodyParameterDescription = apiDescription.ParameterDescriptions.SingleOrDefault(desc => desc.IsFromBody());
447447
if (bodyParameterDescription is not null)
448448
{
449449
contentTypeValue.Schema = GenerateSchema(

test/Swashbuckle.AspNetCore.SwaggerGen.Test/SwaggerGenerator/SwaggerGeneratorTests.cs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2479,6 +2479,46 @@ public void GetSwagger_GenerateConsumesSchemas_ForProvidedOpenApiOperationWithSt
24792479
Assert.Equal(ParameterStyle.Form, content.Value.Encoding["param"].Style);
24802480
}
24812481

2482+
[Fact]
2483+
public void GetSwagger_OpenApiOperationWithRawContent_IsHandled()
2484+
{
2485+
var methodInfo = typeof(FakeController).GetMethod(nameof(FakeController.ActionWithParameter));
2486+
var actionDescriptor = new ActionDescriptor
2487+
{
2488+
EndpointMetadata = new List<object>()
2489+
{
2490+
new OpenApiOperation()
2491+
{
2492+
RequestBody = new OpenApiRequestBody()
2493+
{
2494+
Content = new Dictionary<string, OpenApiMediaType>()
2495+
{
2496+
{ "text/plain", new OpenApiMediaType() }
2497+
}
2498+
}
2499+
}
2500+
},
2501+
RouteValues = new Dictionary<string, string>
2502+
{
2503+
["controller"] = methodInfo.DeclaringType.Name.Replace("Controller", string.Empty)
2504+
}
2505+
};
2506+
var subject = Subject(
2507+
apiDescriptions: new[]
2508+
{
2509+
ApiDescriptionFactory.Create(actionDescriptor, methodInfo, groupName: "v1", httpMethod: "POST", relativePath: "resource"),
2510+
}
2511+
);
2512+
2513+
var document = subject.GetSwagger("v1");
2514+
2515+
Assert.Equal("V1", document.Info.Version);
2516+
Assert.Equal("Test API", document.Info.Title);
2517+
Assert.Equal(new[] { "/resource" }, document.Paths.Keys.ToArray());
2518+
Assert.Equal(new[] { OperationType.Post }, document.Paths["/resource"].Operations.Keys);
2519+
Assert.Single(document.Paths["/resource"].Operations);
2520+
}
2521+
24822522
private static SwaggerGenerator Subject(
24832523
IEnumerable<ApiDescription> apiDescriptions,
24842524
SwaggerGeneratorOptions options = null,

0 commit comments

Comments
 (0)