Skip to content

Instantly share code, notes, and snippets.

@chrcar01
Last active January 20, 2023 20:41
Show Gist options
  • Save chrcar01/c97e0b2a813e8bf6363c270de72774ed to your computer and use it in GitHub Desktop.
Save chrcar01/c97e0b2a813e8bf6363c270de72774ed to your computer and use it in GitHub Desktop.
Async FileStreams: Example of how to produce correct OpenAPI docs for returning files as streams and byte arrays.
async Task Main()
{
var builder = WebApplication.CreateBuilder();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(s => s.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Report API",
Description = "Manager all of your reporting needs.",
Version = "v1",
TermsOfService = null,
License = new OpenApiLicense
{
Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0.html"),
Name = "Apache 2.0"
},
Contact = new OpenApiContact
{
Email = "support@example.com",
Name = "Chris Carter",
Url = new Uri("https://chrisjcarter.com")
}
}));
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(s => s.SwaggerEndpoint("/swagger/v1/swagger.json", "Todo API V1"));
// The file we're going to return from the apis
const string file = @"C:\code\SCA_InfrastructureSecurity_Process.pdf";
// OpenAPI yaml generated for /reports/{id:int}/stream:
/*
'/reports/{id}/stream':
get:
tags:
- Streaming is super cool
operationId: GetReportStream
parameters:
- name: id
in: path
required: true
schema:
type: integer
format: int32
responses:
'200':
description: Success
content:
application/pdf:
schema:
type: string
format: binary
*/
app.MapGet("/reports/{id:int}/stream", (int id) =>
{
var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous);
return Results.File(fileStream, "application/pdf", $"SCA_InfrastructureSecurity_Process_{id}.pdf");
})
.WithName("GetReportStream")
.WithTags("Streaming is super cool")
.Produces((int)HttpStatusCode.OK, typeof(FileStreamResult), "application/pdf");
// OpenAPI yaml generated for /reports/{id:int}/byte-array:
/*
'/reports/{id}/byte-array':
get:
tags:
- Byte arrays are the bees knees.
operationId: GetReportByteArray
parameters:
- name: id
in: path
required: true
schema:
type: integer
format: int32
responses:
'200':
description: Success
content:
application/pdf:
schema:
type: string
format: byte
*/
app.MapGet("/reports/{id:int}/byte-array", async (int id) =>
{
var fileBytes = await File.ReadAllBytesAsync(file);
return Results.File(fileBytes, "application/pdf");
})
.WithName("GetReportByteArray")
.WithTags("Byte arrays are the bees knees.")
.Produces((int)HttpStatusCode.OK, typeof(byte[]), "application/pdf");
await app.RunAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment