(C# ASP.NET Core) Special Types of Implicit Parameter Bindings

ASP.NET Core provides certain "special" parameters that are always available to an api handler. These parameters are "utility" parameters like HttpContext, HttpRequest, HttpResponse, CancellationToken and ClaimsPrincipal. They do not need any attribute decorations like those for the query-string, header, body and route segments.
(Rev. 19-Mar-2024)

Categories | About |     |  


Special parameters do not bind to data

The special parameters are not bound to any request data - they are, rather, instances of utility classes such as the HttpContext and HttpResponse.

No decoration attributes are required, and they are, therefore, also called implicitly bound parameters.

HttpContext contains information about the current request; HttpResponse and HttpRequest provide access to the protocol streams; CancellationToken provides us the ability to cancel the current asynchronous request, and the ClaimsPrincipal is about the user identity associated with the current request.

Video Explanation (see it happen!)

Please watch the following youtube video:

Example Usage

Let's next have a look at an example usage of these types of parameters.

Open the project attached to this video, and locate the program.cs file. Double click to open this file. Scroll to the part that you are seeing here.

app.MapGet("/{id}", (

    HttpRequest req

    ) =>
    String? id = Convert.ToString(req.RouteValues["id"]);

    String? q = Convert.ToString(req.Query["q"]);

    String? ua = Convert.ToString(req.Headers["user-agent"]);

    return Results.Ok($"id={id}, q = {q}, ua = {ua}");

This is a GET web api that receives an HttpRequest as its parameter. It is a special parameter that is implicitly bound to the http request - without any need of attribute decoration.

HttpRequest provides a RouteValues collection to extract the request data associated with a route segment. This is an alternative to the explicit [FromRoute] decoration.

Similarly, we can use the same request to extract query string data from the Query collection.

Request headers can even be read through the Headers collection as you are seeing here.

Run the Project

Run the project with a suitable URL to make a call to this web api. We verify that the api responds and echoes back the data it extracted from the route, the querystring and from the request header. Thank you!

This Blog Post/Article "(C# ASP.NET Core) Special Types of Implicit Parameter Bindings" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.