HTTP HEAD Method in ASP.NET Core Web API

HTTP HEAD Method in ASP.NET Core Web API

In this article, I will discuss How to Implement the HTTP HEAD Method in ASP.NET Core Web API Application with Real-Time Examples. Please read our previous article discussing the HTTP DELETE Method in ASP.NET Core Web API with Examples.

HTTP HEAD Method

The HTTP HEAD method is similar to the GET method in that it requests a response from the server that contains the headers for a specific resource. However, unlike the GET method, the HEAD method does not return the body of the response. This makes the HEAD method particularly useful for retrieving meta-information written in response headers without having to download the entire content. The primary purposes of the HEAD method include:

  • Checking if a Resource Exists: It allows clients to verify the existence of a resource on the server without downloading the actual content. This can be useful for link checking or validating if resources have been updated.
  • Resource Changes and Updates: By requesting only the headers, a client can check the Last-Modified header to determine if the content has changed since the last time it was accessed without downloading the entire resource.
  • Testing Link Validity: The HEAD method can be used to test if a link is valid (i.e., if it leads to a resource that can be successfully retrieved) without the overhead of downloading the resource.
  • Retrieving Header Information: Clients can retrieve metadata about the resource, such as content type (Content-Type header), content length (Content-Length header), and other information about the resource, through the headers.
  • Bandwidth Efficiency: Since the HEAD method does not return the body of the response, it is more bandwidth-efficient for tasks that require only header information.
How Do We Implement HTTP HEAD Method in ASP.NET Core Web API?

The HTTP HEAD method requests headers from a web resource. In the context of ASP.NET Core Web API, it’s a way to retrieve metadata about a resource without fetching the resource itself. Implementing the HEAD method in an ASP.NET Core Web API involves defining a controller action specifically for handling HEAD requests by decorating the action method with HttpHead Attribute. 

Creating Controller:

Create an API Controller and then copy and paste the following code. In your controller, you can explicitly add support for the HEAD method by decorating the action method with the HttpHead attribute. This action should not return the resource but rather set the appropriate headers in the response. The following example code is self-explained, so please go through the comment lines.

using Microsoft.AspNetCore.Mvc;
namespace HTTPMethodDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ResourcesController : ControllerBase
    {
        [HttpGet("GetById/{Id}")]
        public IActionResult GetById(int Id)
        {
            return Ok("Resource Returned");
        }

        // Example method to check if a resource exists
        // URL: api/Resources/CheckResourceExists/1
        [HttpHead("CheckResourceExists/{Id}")]
        public IActionResult CheckResourceExists(int Id)
        {
            // logic to check if the resource exists, e.g., in a database
            // For example, Product with Id, Employee with Id, Order with ID, etc.
            var resourceExists = true;

            if (resourceExists)
            {
                return Ok(); // Returns 200 OK if the resource exists
            }
            else
            {
                return NotFound(); // Returns 404 Not Found if the resource does not exist
            }
        }

        // Detecting Resource Changes and Updates
        // URL: api/Resources//1
        [HttpHead("GetResourceInfo/{Id}")]
        public IActionResult GetResourceHeaders(int Id)
        {
            // logic to retrieve resource details, e.g., from a database
            var resourceMetadata = new
            {
                LastModified = DateTime.UtcNow,
                CustomHeader = "ABCDZYZ"
            };

            Response.Headers.Add("Last-Modified", resourceMetadata.LastModified.ToString("R")); // RFC1123 format
            Response.Headers.Add("CustomHeader", resourceMetadata.CustomHeader);
            return Ok();
        }

        // Retrieving Header Information
        // URL: api/Resources/GetResourceHeaders/1
        [HttpHead("GetResourceHeaders/{Id}")]
        public IActionResult GetResourceInfo(int Id)
        {
            // logic to find resource and get the Resource Headers
            var resource = new
            {
                ContentType = "application/json",
                ContentLength = 1234 //bytes
            };

            if (resource == null)
            {
                return NotFound();
            }

            // Add desired headers
            Response.Headers.Add("Content-Type", resource.ContentType);
            Response.Headers.Add("Content-Length", resource.ContentLength.ToString());
            // Additional headers as needed

            return Ok();
        }
    }
}
Testing the API Endpoints:

Let us test the above endpoints using HTTP HEAD Requests.

API 1: Check if a Resource Exists

URL: https://localhost:7047/api/Resources/CheckResourceExists/1

Method: HEAD

Response Header using Postman:

How to Implement the HTTP HEAD Method in ASP.NET Core Web API with Examples

API 2: Detecting Resource Changes and Updates

URL: https://localhost:7047/api/Resources/GetResourceInfo/1

Method: HEAD

Response Header using Postman:

How to Implement the HTTP HEAD Method in ASP.NET Core Web API

API 3: Retrieving Header Information

URL: https://localhost:7047/api/Resources/GetResourceHeaders/1

Method: HEAD

Response Header using Postman:

HTTP HEAD Method in ASP.NET Core Web API

When Should We Use HTTP HEAD Method in ASP.NET Core Web API?

In ASP.NET Core Web API, the HTTP HEAD method is used in scenarios where a client wants to retrieve the headers of a resource without fetching the resource itself. This can be particularly useful in several cases, such as:

  • Checking Resource Existence or Accessibility: Before downloading a large file or a resource, a client might send a HEAD request to check if the resource exists and is accessible. This can save bandwidth and processing time by avoiding downloading large files that are not needed or accessible.
  • Resource Metadata: Clients might be interested in the metadata of a resource, such as its last-modified date, content type, or content length, without needing the resource itself. The HEAD method allows clients to get this metadata efficiently.
  • Cache Validation: The HEAD method can be used to validate cached resources. A client can send a HEAD request with the If-Modified-Since header to check if the resource has been modified since it was cached. If the server responds with a 304 Not Modified status, the client can continue to use the cached version, saving bandwidth and server resources.
  • Monitoring Web Server and Resource Health: Automated systems can use HEAD requests to monitor the health and availability of web servers and specific resources. This is a lightweight method to ensure that a server is responsive and that specific resources are available without fetching the entire resource.

In the next article, I will discuss How to Implement the HTTP OPTIONS Method in ASP.NET Core Web API Application with Examples. In this article, I explain How to Implement the HTTP HEAD Method in ASP.NET Core Web API with Examples. I hope you enjoy this article, ” HTTP HEAD Method in ASP.NET Core Web API.”

Leave a Reply

Your email address will not be published. Required fields are marked *