Start learning free

LESSON 117 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Serve the Photo in C#

Practice

A page shows a product's photo with a tag like <img src="/products/1/photo">. The browser sends a GET to that address and draws whatever image comes back. So the shop answers the photo's bytes as they are, not JSON.

Bytes don't say what they are. The answer's Content-Type header tells the browser how to read them: image/png, image/jpeg... Results.Json always sets it to application/json; for bytes, you choose it. Results.Bytes(bytes, contentType) answers the bytes with status 200 and that Content-Type. For example, a route that answers plain text as bytes:

app.MapGet("/robots.txt", () => {
    var bytes = Encoding.UTF8.GetBytes("User-agent: *");
    return Results.Bytes(bytes, "text/plain");
});

FileExtensionContentTypeProvider, from Microsoft.AspNetCore.StaticFiles (already in your usings), knows the type of each file extension. new FileExtensionContentTypeProvider().TryGetContentType("report.pdf", out var type) returns true when it knows the extension, and puts the type, "application/pdf", into the out variable type.

After the tests upload two photos, the shop must answer:

POST /products/1/photo  (photo: mug.png, 16 bytes)  →  201  {"filename": "mug.png", "product_id": 1, "size": 16}
POST /products/3/photo  (photo: lamp.jpg, 17 bytes)  →  201  {"filename": "lamp.jpg", "product_id": 3, "size": 17}
GET /products/1/photo  →  200  Content-Type: image/png, the 16 bytes
GET /products/3/photo  →  200  Content-Type: image/jpeg, the 17 bytes
GET /products/2/photo  →  404  {"error": "This product has no photo"}

Your task: add GET /products/{id}/photo. Look up the product's row in photos; with no row, answer 404; otherwise answer the stored bytes with status 200 and the Content-Type for the photo's file name.


Assignment
Follow the Coding Tutorial to add the route that serves a product's photo.


Hint
(string)row["filename"] and (byte[])row["data"] give the name and the bytes of the row. Until the route's last return is written, C# stops with CS1643: not all code paths return a value.


STEP 1 OF 8
    Ctrl + Enter to check

    Files Serve in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free