Course Content
About Minimal APIs
0/1
Naming Conventions
0/1
Implementing the Result Pattern in Minimal APIs
0/2
Minimal APIs in ASP.NET Core

Since a HEAD request is essentially a GET request without a body, we can share logic with GET endpoints while ignoring the response body. To see how this works in practice, let’s open our main project, navigate to the Endpoints folder, and open the ProjectEndpoints class:

group.MapMethods("", ["GET", "HEAD"], async (
    [AsParameters] ProjectRequestParameters requestParams,
    [FromServices] IServiceManager serviceManager,
    HttpContext context,
    CancellationToken cancellationToken) =>
{
    var projects = await serviceManager.ProjectService
            .GetPagedProjectsAsync(requestParams, cancellationToken);

    if (context.Request.Method is "HEAD")
    {
        return Results.Ok();
    }

    if (context.Request.Headers.Accept.Contains("application/xml"))
    {
        return new XmlResult(projects);
    }

    return Results.Ok(projects);
})
.CacheOutput("FiveMinutes")
.Produces<PagedList<ProjectResponse>>()
.WithName(ProjectConstants.GetAllProjects);

Here, we update our endpoint responsible for fetching all projects. We start by replacing the MapGet() method with the MapMethods(). Then, after the route pattern, we pass a new string collection that contains the names of the GET and HEAD methods. By doing this, we specify that this endpoint will be responsible for handling both types of requests.

Inside the route handler itself, we check if the method of the request is HEAD, and if it is, we return 200 OK but with no response body.

After the endpoint modification is done, we can open Postman, authenticate ourselves, and send a HEAD request:

curl --location --head 'https://localhost:5001/api/v1/projects' \
--header 'Authorization: Bearer ******'

We get 200 OK as expected. We also get an empty body and the response contains only headers.

Let’s send another request, this time a GET one to the same address just to ensure we haven’t broken our API:

curl --location 'https://localhost:5001/api/v1/projects' \
--header 'Authorization: Bearer ******'

It works the same as before we introduced our new logic to handle HEAD requests. Great!

Next, we’ll tackle the OPTIONS method.

0% Complete