Search code examples
c#asp.net-mvchttp-gethttp-head

Add support for [HttpHead] and [HttpGet] in MVC controller method


I have an MVC method as follows which supports the [HttpGet] attribute.

[HttpGet]        
[ActionName("Index")]
public ActionResult IndexGet(string l)
{               
    return View();
}

However, I'm noticing in our web server log files we are getting a HEAD request, but since I don't have a [HttpHead] defined we are returning a 404, which is correct. The web server log file entries are for example

2020-05-20 00:00:51 W3SVC1 EC2AMAZ 10.0.0.206 HEAD / 443 - XXX.XXX.XXX.XXX HTTP/1.1 Mozilla/5.0+(compatible;+UptimeRobot/2.0;+http://www.uptimerobot.com/) - www.domainname.com 404 0 0 306 694 155

and

2020-05-20 00:01:13 W3SVC1 EC2AMAZ 10.0.0.206 GET / 443 - XXX.XXX.XXX.XXX HTTP/1.1 Mozilla/5.0+(compatible;+UptimeRobot/2.0;+http://www.uptimerobot.com/) - www.domainname.com 200 0 0 156847 674 1065

How can I add support for [HttpHead] and what should I return in the response. I tried adding both [HttpHead] and [HttpGet]

[HttpHead]  
[HttpGet]       
[ActionName("Index")]
public ActionResult IndexGet(string l)
{               
    return View();
}

but get the following in the browser

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

and it breaks the [HttpGet] method. If I remove the [HttpHead] and refresh the URL the [HttpGet] loads fine.


Solution

  • A HEAD request should respond with only headers, not content. So mixing with a GET shouldn't be done.

    The easiest option is to create an extra method in the controller to handle that HEAD request:

    [HttpHead]
    [ActionName("Index")]
    public ActionResult IsAlive()
    {
       return Ok();
    }