Introduction

Welcome to the final lesson of our course on model binding in Minimal APIs! Throughout this course, we've explored what model binding is and how it seamlessly maps incoming HTTP request data to handler parameters. We've covered binding both simple and complex types, and making those parameters optional to build versatile and robust APIs. In this lesson, we'll focus on binding special types, such as HttpContext, HttpRequest, and others.

Binding HttpContext and Other Types

Let's start by delving into HttpContext, an object created with every incoming request to your minimal API. It encapsulates all HTTP-specific information about the request. Alongside HttpContext, several other related types like HttpRequest, HttpResponse, and ClaimsPrincipal can also be directly bound.

Here is an example demonstrating how to bind and use HttpContext and ClaimsPrincipal:

In the code snippet above:

  • app.MapGet("/inspect", ...): Establishes a GET endpoint at /inspect.
  • HttpContext context: Binds the HttpContext to access request data and server info.
  • ClaimsPrincipal user: Binds the authenticated user's principal.
  • context.Request.Path: Extracts the path of the current request.
  • user.Identity?.Name: Retrieves the name of the authenticated user, if available.
Available Common Types

Below is a table summarizing the different types that can be bound and their descriptions along with commonly used properties:

TypeDescriptionCommonly Used Properties
HttpContextComprehensive details about both the request and the response. It's the central hub for HTTP data.Request, Response, User, Items, Features
HttpRequestContains details specifically about the request, equivalent to HttpContext.Request.Method, Path, Headers, Query, Body
HttpResponseContains details specifically about the response, equivalent to HttpContext.Response.StatusCode, , ,
Summary

In this lesson, you learned how to bind HttpContext and other related types in minimal APIs. This concludes our course on model binding. Up next, get ready to practice and apply what you've learned. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal