Возможно ли создать запрос HTTP HEAD с новым HttpClient
в .NET 4.5? Единственными методами, которые я могу найти, являются GetAsync
, DeleteAsync
, PutAsync
и PostAsync
. Я знаю, что класс HttpWebRequest
способен это сделать, но я хочу использовать современный HttpClient
.
HTTP HEAD с HttpClient в .NET 4.5 и С#
Ответ 1
Используйте метод SendAsync
с экземпляром HttpRequestMessage
, который был создан с использованием HttpMethod.Head
.
GetAsync
, PostAsync
и т.д. удобные обертки вокруг SendAsync
; менее распространенные HTTP-методы, такие как HEAD
, OPTIONS
и т.д., не получают оболочку.
Ответ 2
Мне нужно было сделать это, чтобы получить TotalCount
банкоматов, которые я возвращал из своего метода веб-API GET.
Когда я попробовал ответить @Smig, я получил следующий ответ от моего веб-API.
МетодNotAllowed: Pragma: no-cache X-SourceFiles: =? UTF-8? B? dfdsf Cache-Control: no-cache Дата: ср, 22 марта 2017 20:42:57 GMT Сервер: Microsoft-IIS/10.0 X-AspNet-версия: 4.0.30319 X-Powered-By: ASP.NET
Пришлось на основе ответа @Smig, чтобы эта работа успешно работала. Я узнал, что методы Web API должны явно разрешать глагол Http 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 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.
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()}");
}
В веб-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
}
}