Junior — Middle
How is an incoming request transformed into method parameters in a controller?
sobes.tech AI
Answer from AI
In ASP.NET, controllers receive method parameters from incoming HTTP requests using the model binding mechanism.
When a request arrives, the framework analyzes data from various sources:
- Query string parameters
- Request body (e.g., JSON or form-data)
- Headers
- Route parameters
And attempts to match them with the controller method parameters by name and type.
For example, if a controller method looks like this:
public IActionResult GetUser(int id, string name)
The framework will look for id and name parameters in the request and automatically convert them to the required types.
For complex objects, attributes like [FromBody], [FromQuery], etc., can be used to explicitly specify the data source.
Example:
[HttpPost]
public IActionResult CreateUser([FromBody] UserModel user)
Here, the JSON from the request body will be deserialized into a UserModel object and passed to the method.