简体   繁体   中英

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.

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();
}

The HttpGet or HttpHead attributes represents an attribute that is used to restrict an action method so that the method handles only HTTP GET requests or only HTTP HEAD requests. A request cannot be both of these so combining them causes the controller method never to match and the result is a 404 response.

The correct way to allow both GET and HEAD requests for a single controller method is to use:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
    

See the accepted answer to Respond to HTTP HEAD requests using ASP.NET MVC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM