Start learning free

LESSON 25 OF 173 · BACKEND: YOUR FIRST API

Methods a Path Allows

Practice

Each route answers one method on one path. When a request comes for a path that exists, but with a method no route handles, ASP.NET Core answers 405 Method Not Allowed. With it, it sends an Allow header: the list of methods the path does accept. A path with no route at all still gets 404 Not Found.

For example, / has only a GET route, so DELETE / gets 405 with Allow: GET. You never write code for a 405: to allow a method on a path, you add a route for it.

That's what you'll do for /about. Its answer used to be written inside the function, so nothing could change it. You'll keep the shop's details in a dictionary shop that both routes share, and add a PUT route that replaces them. The requests and answers your code must give, in this order:

PUT /products  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  405  Allow: GET, POST
POST /products/2  {"price": 5}
  →  405  Allow: DELETE, GET, PATCH, PUT
DELETE /about  →  405  Allow: GET, PUT
PUT /about  {"name": "Corner Store", "currency": "EUR"}
  →  200  {"name": "Corner Store", "currency": "EUR"}
GET /about  →  200  {"name": "Corner Store", "currency": "EUR"}
GET /contact  →  404

Your task: keep the about details in a Dictionary<string, string> named shop, make GET /about answer it, and add PUT /about with app.MapPut, which replaces the name and currency with the ones in the body and answers the new details. Then /about allows GET and PUT.


Assignment
Follow the Coding Tutorial to store the shop's details in a variable and add a PUT route for /about.


Hint
shop lives outside the route functions, so both routes read and change the same dictionary. The 405 answers need no code: ASP.NET Core sends them, with the Allow header, for every method a path has no route for.


STEP 1 OF 6
    Ctrl + Enter to check