60

HttpClient是否可以使用.NET 4.5 中的新功能创建 HTTP HEAD 请求?我能找到的唯一方法是GetAsyncDeleteAsync和。我知道-class 能够做到这一点,但我想使用现代的.PutAsyncPostAsyncHttpWebRequestHttpClient

4

4 回答 4

109

将该SendAsync方法与使用HttpRequestMessage构造的实例一起使用HttpMethod.Head

GetAsync, PostAsync, etc 是方便的包装器SendAsync;不太常见的 HTTP 方法(例如HEAD,OPTIONS等)没有包装器。

简而言之:

client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url))

于 2013-05-07T10:54:50.653 回答
17

您还可以执行以下操作来仅获取标头:

this.GetAsync($"http://url.com", HttpCompletionOption.ResponseHeadersRead).Result;
于 2018-06-20T20:38:07.520 回答
6

我需要这样做,以获取TotalCount从我的 Web APIGET方法返回的 ATM。

当我尝试@Smig 的回答时,我从我的 Web API 中得到了以下响应。

MethodNotAllowed : Pragma: no-cache X-SourceFiles: =?UTF-8?B?dfdsf Cache-Control: no-cache 日期: Wed, 22 Mar 2017 20:42:57 GMT 服务器: Microsoft-IIS/10.0 X-AspNet -版本:4.0.30319 X-Powered-By:ASP.NET

必须以@Smig 的回答为基础才能成功完成这项工作。我发现 Web API 方法需要通过在ActionHttp HEAD方法中将动词指定为属性来明确允许动词。

这是通过代码注释的内联解释的完整代码。我已经删除了敏感代码。

在我的网络客户端中:

        HttpClient client = new HttpClient();

        // set the base host address for the Api (comes from Web.Config)
        client.BaseAddress = new Uri(ConfigurationManager.AppSettings.Get("ApiBase"));
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add( 
          new MediaTypeWithQualityHeaderValue("application/json"));

        // Construct the HEAD only needed request. Note that I am requesting
        //  only the 1st page and 1st record from my API's endpoint.
        HttpRequestMessage request = new HttpRequestMessage(
          HttpMethod.Head, 
          "api/atms?page=1&pagesize=1");

        HttpResponseMessage response = await client.SendAsync(request);

        // FindAndParsePagingInfo is a simple helper I wrote that parses the 
        // json in the Header and populates a PagingInfo poco that contains 
        // paging info like CurrentPage, TotalPages, and TotalCount, which 
        // is the total number of records in the ATMs table.
        // The source code is pasted separately in this answer.
        var pagingInfoForAtms = HeaderParser.FindAndParsePagingInfo(response.Headers);

        if (response.IsSuccessStatusCode)
            // This for testing only. pagingInfoForAtms.TotalCount correctly
            //  contained the record count
            return Content($"# of ATMs {pagingInfoForAtms.TotalCount}");

            // if request failed, execution will come through to this line 
            // and display the response status code and message. This is how
            //  I found out that I had to specify the HttpHead attribute.
            return Content($"{response.StatusCode} : {response.Headers.ToString()}");
        }

在 Web API 中。

    // Specify the HttpHead attribute to avoid getting the MethodNotAllowed error.
    [HttpGet, HttpHead]
    [Route("Atms", Name = "AtmsList")]
    public IHttpActionResult Get(string sort="id", int page = 1, int pageSize = 5)
    {
        try
        {
            // get data from repository
            var atms =  _atmRepository.GetAll().AsQueryable().ApplySort(sort);
            // ... do some code to construct pagingInfo etc.
            // .......
            // set paging info in header.
            HttpContext.Current.Response.Headers.Add(
              "X-Pagination", JsonConvert.SerializeObject(paginationHeader));
            // ...
            return Ok(pagedAtms));
        }
        catch (Exception exception)
        {
            //... log and return 500 error
        }
    }

FindAndParsePagingInfo Helper 方法,用于解析分页头数据。

public static class HeaderParser
{
public static PagingInfo FindAndParsePagingInfo(HttpResponseHeaders responseHeaders)
{
    // find the "X-Pagination" info in header
    if (responseHeaders.Contains("X-Pagination"))
    {
        var xPag = responseHeaders.First(ph => ph.Key == "X-Pagination").Value;

        // parse the value - this is a JSON-string.
        return JsonConvert.DeserializeObject<PagingInfo>(xPag.First());
    }

    return null;
}

public static string GetSingleHeaderValue(HttpResponseHeaders responseHeaders, 
    string keyName)
{
    if (responseHeaders.Contains(keyName))
        return responseHeaders.First(ph => ph.Key == keyName).Value.First();

    return null;
}

}

于 2017-03-22T21:04:14.120 回答
2

通过做解决了它

 var result = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
于 2020-06-18T09:30:46.137 回答