是否有可能创建新的HTTP一个HEAD请求HttpClient
在.NET 4.5? 唯一的方法我能看到的是GetAsync
, DeleteAsync
, PutAsync
和PostAsync
。 我知道HttpWebRequest
-class是能够做到这一点,但我想用现代HttpClient
。
Answer 1:
使用SendAsync
与实例方法HttpRequestMessage
这是利用人工HttpMethod.Head
。
GetAsync
, PostAsync
等都是方便的包装围绕SendAsync
; 不太常见的HTTP方法,如HEAD
, OPTIONS
等,没有得到的包装。
Answer 2:
我需要做到这一点,让TotalCount
,我是从我的Web API的get方法返回自动取款机。
当我试图@ SMIG的回答,我从我的Web API以下响应。
MethodNotAllowed:杂注:无缓存X-SourceFiles:= UTF-的8B dfdsf的Cache-Control:???无缓存时间:星期三,2017年3月22日20点42分五十七秒格林尼治标准时间服务器:Microsoft-IIS / 10.0 X-ASPNET -version:4.0.30319 X供电-者:ASP.NET
只好在@内置SMIG的回答让这个成功的工作。 我发现在Web API方法需要明确允许Http HEAD
在操作方法为属性指定它的动词。
下面是由代码注释的方式直列解释的完整代码。 我已经删除了敏感的代码。
在我的Web客户端:
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;
}
}
Answer 3:
你也可以做如下去取只是标题:
this.GetAsync($"http://url.com", HttpCompletionOption.ResponseHeadersRead).Result;
文章来源: HTTP HEAD request with HttpClient in .NET 4.5 and C#