StaffCoder
.NET
.NET.NET 10
12 modules · 48 challengesSign up
Module 4 · Model Binding and Validation

Registration Payload Binding

easy100%1 of 1 solved

Problem statement

Map a signup endpoint that binds the JSON body to a typed record, so a body that cannot be read is answered with 400 before any of your code runs.

Requirements

The SignupRequest record and ISignupService are already provided and registered. Your task has one part: map POST /signups in MapSignupEndpoints in SignupApi/Endpoints/SignupEndpoints.cs.

In a minimal API, a handler parameter of a record or class type is bound from the JSON request body. When the body is not valid JSON, or a value has the wrong type, ASP.NET Core answers 400 by itself and the handler is never called.

ISignupService (provided)

  • Register(request) stores the signup and returns it with its new signupId
  • GET /signups/attempts reports handlerCalls, the number of times Register was called

SignupEndpoints

  • POST /signups takes a SignupRequest from the JSON body and answers 200 with the result of Register
  • Every property of the body arrives in the record: email, displayName, age and acceptsMarketing
  • A body that cannot be read, such as cut-off JSON, text that is not JSON, or age given as "thirty", is answered with 400, and Register is not called
  • The endpoint declares SignupRequest as its request body, so the body is bound by the framework and not read by hand
Sample Requests & Responses

POST /signups

Request body:

{ "email": "ada@example.com", "displayName": "Ada Lovelace", "age": 36, "acceptsMarketing": true }

Response (200 OK):

{ "signupId": 1, "email": "ada@example.com", "displayName": "Ada Lovelace", "age": 36, "acceptsMarketing": true }

POST /signups with the cut-off body { "email": "ada@example.com", "displayName": "Ada

Response (400 Bad Request).

GET /signups/attempts after the two requests above

Response (200 OK), showing that only the valid body reached the handler:

{ "handlerCalls": 1 }

More in Model Binding and Validation

See the module
Annotated Product ValidationThis problem covers adding validation attributes to a model and answering an invalid one with validation problem details that name every failing field.100%1 of 1 solvedeasyHeader And Query Metadata BindingThis problem covers binding a required value from a request header and an optional value with a default from the query string straight into an action's parameters.100%1 of 1 solvedeasyOrder Submission EndpointThis problem covers binding a route id, a validated JSON body, a required header and an optional query value in one endpoint, and answering bad input with validation problem details naming each failing field.100%1 of 1 solvedeasy

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.