41

当机器人使用 HEAD 访问我的 ASP.NET MVC 站点时,我想正确支持 HTTP HEAD 请求。我注意到该站点的所有 HTTP HEAD 请求都返回 404,尤其是来自http://downforeveryoneorjustme.com的请求。这真的很烦人。希望他们能像其他所有优秀的机器人一样切换到 GET。

如果我只是更改[AcceptVerbs(HttpVerbs.Get)][AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]MVC 会知道删除请求的正文吗?

你做了什么来支持 HTTP HEAD 请求?(代码示例会很棒!)

4

2 回答 2

57

I created a simple action method in an ASP.Net MVC 2 project:

public class HomeController : Controller
{
    public ActionResult TestMe()
    {
        return View();
    }
}

Then I launched Fiddler and built up an HTTP GET request to hit this URL:

http://localhost.:51149/Home/TestMe

The expected full page content was returned.

Then, I changed the request to use an HTTP HEAD instead of an HTTP GET. I received just the expected head info and no body info in the raw output.

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 07 Jul 2010 16:58:55 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 2.0
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 1120
Connection: Close

My guess is that you are including a constraint on the action method such that it will only respond to HTTP GET verbs. If you do something like this, it will work for both GET and HEAD, or you can omit the constraint entirely if it provides no value.

public class HomeController : Controller
{
    [AcceptVerbs(new[] {"GET", "HEAD"})]
    public ActionResult TestMe()
    {
        return View();
    }
}
于 2010-07-07T17:06:17.637 回答
29

您只需执行以下操作即可获得结果

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
public ActionResult TestMe() =>View();
于 2013-02-23T08:11:35.067 回答