Returning Files
An endpoint can answer with a file instead of JSON: a CSV export, a generated report, a document already stored in the workspace. The caller receives the file's bytes with its content type and a Content-Disposition: attachment header carrying the file name, so a browser saves it as a download.
The endpoint returns one of these values:
| Return value | Content type | File name |
|---|---|---|
FileResponse.FromString(fileName, contentType, text) |
contentType |
fileName |
FileResponse.FromStream(fileName, contentType, stream) |
contentType |
fileName |
FileResponse.FromUID(uid, fileName?, contentType?) |
the stored file's, unless given | the stored file's, unless given |
A PdfSharp.Pdf.PdfDocument |
application/pdf |
the document's Info.Title + .pdf, or Document.pdf |
An NPOI IWorkbook (for example XSSFWorkbook) |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
the first sheet's name + .xlsx |
FileResponse lives in Mosaik.CodeEndpoints.Responses. That namespace, PdfSharp, NPOI.SS.UserModel and NPOI.XSSF.UserModel are imported in every endpoint, so none of these needs a using.
Text content
FileResponse.FromString encodes the text as UTF-8. Use it for CSV, Markdown, JSON Lines, or any other text format you build in memory.
var csv = new System.Text.StringBuilder();
csv.AppendLine("Id,Summary,Status");
foreach (var node in Q().StartAt(N.SupportCase.Type).AsEnumerable())
{
var summary = node.GetString(N.SupportCase.Summary).Replace("\"", "\"\"");
csv.AppendLine($"{node.GetString(N.SupportCase.Id)},\"{summary}\",{node.GetString(N.SupportCase.Status)}");
}
return FileResponse.FromString("support-cases.csv", "text/csv", csv.ToString());
A query can write itself as CSV or JSON Lines with ToCsvAsync and ToJsonLinesAsync (see Graph Query Language). Both leave the stream open, so rewind it and hand it to FromStream:
var stream = new MemoryStream();
await Q().StartAt(N.SupportCase.Type)
.WhereString(N.SupportCase.Type, N.SupportCase.Status, "Open")
.ToCsvAsync(stream, cancellationToken: CancellationToken);
stream.Position = 0;
return FileResponse.FromStream("open-cases.csv", "text/csv", stream);
Binary content
FileResponse.FromStream sends any stream. The server copies it to a temporary file before it answers, then disposes it, so the stream does not have to outlive the endpoint's code.
public record ArchiveRequest(string[] CaseIds);
var req = ParseBody<ArchiveRequest>();
var zip = new MemoryStream();
using (var archive = new System.IO.Compression.ZipArchive(zip, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true))
{
foreach (var id in req.CaseIds)
{
if (!Graph.TryGet(N.SupportCase.Type, id, out var node)) continue;
var entry = archive.CreateEntry($"{id}.txt");
using var writer = new StreamWriter(entry.Open());
writer.Write(node.GetString(N.SupportCase.Summary));
}
}
zip.Position = 0;
return FileResponse.FromStream("cases.zip", "application/zip", zip);
Rewind the stream
The server reads the stream from its current position. A MemoryStream you just wrote to is positioned at its end and produces an empty file unless you set Position = 0 first.
Files stored in the workspace
FileResponse.FromUID names a file that is already in the workspace: a _FileEntry node (an uploaded or ingested file) or the _Blob behind one. The endpoint does not read the content; the server reads it after the endpoint returns.
var fileUID = ParseBody<UID128>();
return FileResponse.FromUID(fileUID);
Pass a file name or content type to override the stored ones:
return FileResponse.FromUID(fileUID, fileName: "contract-signed.pdf", contentType: "application/pdf");
The server reads the file as the calling user. If that user cannot access the file (for a blob, the node that holds it), the call fails instead of returning the bytes, so an endpoint cannot hand out a file the caller could not have downloaded from the workspace themselves. A UID that is not a file or a blob also fails.
Calls made with an endpoint token
An endpoint called with an endpoint token runs with no user (CurrentUser is default), and then no access check is made: the token holder receives any file whose UID they send. Check the UID against what the caller is allowed to download before returning it, or don't take file UIDs from the request body on token-called endpoints.
PDF documents and Excel workbooks
Return a PdfSharp PdfDocument or an NPOI IWorkbook directly; the server saves it in its format and picks the content type.
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("Open cases"); // downloads as "Open cases.xlsx"
var header = sheet.CreateRow(0);
header.CreateCell(0).SetCellValue("Id");
header.CreateCell(1).SetCellValue("Summary");
var rowIndex = 1;
foreach (var node in Q().StartAt(N.SupportCase.Type).WhereString(N.SupportCase.Type, N.SupportCase.Status, "Open").AsEnumerable())
{
var row = sheet.CreateRow(rowIndex++);
row.CreateCell(0).SetCellValue(node.GetString(N.SupportCase.Id));
row.CreateCell(1).SetCellValue(node.GetString(N.SupportCase.Summary));
}
return workbook;
To control the file name of a PDF or workbook, save it to a MemoryStream and return a FileResponse instead:
var stream = new MemoryStream();
workbook.Write(stream, leaveOpen: true);
stream.Position = 0;
return FileResponse.FromStream($"cases-{DateTime.UtcNow:yyyy-MM-dd}.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
stream);
Status code and content type
Wrap any of the values above in Ok, StatusCode or the other response helpers from the execution scope. A content type passed to the helper replaces the file's own:
var caseId = ParseBody<string>();
if (!Graph.TryGet(N.SupportCase.Type, caseId, out var node))
return NotFound("No such case.");
return Ok(FileResponse.FromString($"{caseId}.md", "text/markdown", node.GetString(N.SupportCase.Summary)),
"text/markdown; charset=utf-8");
Downloading the file
Files work with both Sync and Pooling endpoints. In Pooling mode the caller keeps polling until it gets 200 OK, and the file is the body of that response.
Mosaik.API.Endpoints.DownloadAsync calls the endpoint and saves the response in the browser under the file name the endpoint returned. It handles pooling the same way CallAsync does.
await Mosaik.API.Endpoints.DownloadAsync("reports/open-cases");
// With a request body
await Mosaik.API.Endpoints.DownloadAsync("cases/archive", new { CaseIds = new[] { "C-1001", "C-1002" } });
Don't use CallAsync<string> for a file: it reads the response as text, which corrupts binary content.
The file name in the Content-Disposition header is URL-encoded, so a name with spaces arrives as Open+cases.xlsx to a client that reads the header literally (for example curl -OJ). Name the output file yourself, as above, when that matters.
Related
- Execution scopes:
Ok,StatusCodeand the other response helpers. - Calling endpoints: URLs, tokens and pooling.
- Security best practices