Problem statement
Add validation attributes to a product and answer an invalid one with a validation problem that names every failing field.
Requirements
The product store and GET /products are already provided. Your task has two parts: add validation attributes in ProductCatalogApi/Models/Product.cs, and reject an invalid product in CreateProduct in ProductCatalogApi/Controllers/ProductsController.cs.
Validation attributes such as [Required], [StringLength] and [Range] describe a valid value. ASP.NET Core checks them while binding the body and records each failure in ModelState. In this app the automatic 400 is switched off, so the action decides what to answer.
Product
- Name is required: a missing, empty or blank name is invalid
- Name has from 3 to 60 characters
- Price is from 0.01 to 10000
- StockQuantity is from 0 to 5000
ProductsController
- When ModelState is not valid, POST /products answers 400 with validation problem details (application/problem+json), whose errors name each failing field, and the product is not stored
- A valid product is stored and answered with 201, as the rest of CreateProduct already does
Sample Requests & Responses
POST /products
Request body:
{ "name": "Desk Lamp", "price": 45.00, "stockQuantity": 10 }
Response (201 Created), with the header Location: /products/1:
{ "id": 1, "name": "Desk Lamp", "price": 45.00, "stockQuantity": 10 }
POST /products with { "name": "x", "price": -1, "stockQuantity": 6000 }
Response (400 Bad Request), as application/problem+json:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Name": ["The field Name must be a string with a minimum length of 3 and a maximum length of 60."],
"Price": ["The field Price must be between 0.01 and 10000."],
"StockQuantity": ["The field StockQuantity must be between 0 and 5000."]
}
}
