Start learning free

LESSON 170 OF 173 · BACKEND: YOUR OWN API

Short Links: Redirect

Practice

The app stores short links, but a short link is only useful if opening it takes you to the long URL. A short link is the app's address, a slash, then the code: /1, /zz.

Any text in the path: a route like "/{code}", with no constraint such as {code:int}, takes any text between the slashes and hands it to the function's string parameter of the same name. That suits codes made of digits and letters.

Redirects: Results.Redirect(url) makes an answer with the status 302 Found and a Location header set to the URL. The answer has no page of its own: a browser that gets it opens that URL right away. For example, on another route:

app.MapGet("/docs", () => {
    return Results.Redirect("https://learn.microsoft.com/aspnet/core/");
});

After two POST /links made the codes 1 and 2, your app must answer:

GET /1   →  302  Location: https://www.python.org/downloads/
GET /2   →  302  Location: https://en.wikipedia.org/wiki/URL_shortening
GET /3   →  404  {"error": "Link not found"}
GET /zz  →  404  {"error": "Link not found"}

And once a third POST /links made the code 3:

GET /3   →  302  Location: https://flask.palletsprojects.com/en/stable/quickstart/

Your task: at the end of the file, add GET /{code}. When links doesn't contain the code, answer 404 with {"error": "Link not found"}; otherwise redirect to the stored URL.


Assignment
Follow the Coding Tutorial to add the GET /{code} route that sends a short link on to its long URL.


Hint
The function's parameter has the same name as the part in curly braces. Check for a missing code first and return the 404; only then read links[code]. Every path through the function must return an answer, or C# won't compile it.


STEP 1 OF 4
    Ctrl + Enter to check