HttpResponseHeaderCollection Класс

Определение

Предоставляет коллекцию заголовков HTTP, связанных с HTTP-ответом.

public ref class HttpResponseHeaderCollection sealed : IIterable<IKeyValuePair<Platform::String ^, Platform::String ^> ^>, IMap<Platform::String ^, Platform::String ^>, IStringable
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class HttpResponseHeaderCollection final : IIterable<IKeyValuePair<winrt::hstring, winrt::hstring const&>>, IMap<winrt::hstring, winrt::hstring const&>, IStringable
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
class HttpResponseHeaderCollection final : IIterable<IKeyValuePair<winrt::hstring, winrt::hstring const&>>, IMap<winrt::hstring, winrt::hstring const&>, IStringable
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class HttpResponseHeaderCollection : IDictionary<string,string>, IEnumerable<KeyValuePair<string,string>>, IStringable
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
public sealed class HttpResponseHeaderCollection : IDictionary<string,string>, IEnumerable<KeyValuePair<string,string>>, IStringable
Public NotInheritable Class HttpResponseHeaderCollection
Implements IDictionary(Of String, String), IEnumerable(Of KeyValuePair(Of String, String)), IStringable
Наследование
Object Platform::Object IInspectable HttpResponseHeaderCollection
Атрибуты
Реализации
IDictionary<String,String> IMap<Platform::String,Platform::String> IMap<winrt::hstring,winrt::hstring> IIterable<IKeyValuePair<K,V>> IEnumerable<KeyValuePair<K,V>> IEnumerable<KeyValuePair<String,String>> IIterable<IKeyValuePair<Platform::String,Platform::String>> IIterable<IKeyValuePair<winrt::hstring,winrt::hstring>> IStringable

Требования к Windows

Семейство устройств
Windows 10 (появилось в 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (появилось в v1.0)

Примеры

В следующем примере кода показан метод для получения и задания заголовков ответов в объекте HttpResponseMessage с помощью свойств объекта HttpResponseHeaderCollection. Пространство имен Windows.Web.Http.Headers содержит ряд строго типизированных коллекций заголовков и классов значений для определенных http-заголовков, которые можно использовать для получения и задания заголовков с проверкой.

using System;
using System.Collections.Generic;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Web.Http;
using Windows.Web.Http.Headers;

        void DemonstrateResponseHeaders() {

            DemonstrateHeaderResponseAge();
            DemonstrateHeaderResponseAllow();
            DemonstrateHeaderResponseCacheControl();
            DemonstrateHeaderResponseDate();
            DemonstrateHeaderResponseLocation();
            DemonstrateHeaderResponseProxyAuthenticate();

        }


        public void DemonstrateHeaderResponseAge()
        {
            var response = new HttpResponseMessage();

            // Set the header with a strong type.
            DateTimeOffset value = DateTimeOffset.UtcNow;
            response.Headers.Age = new TimeSpan(1, 35, 55); // 1 hour, 35 minutes, 55 seconds.

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("Age value in minutes: {0}", response.Headers.Age.Value.TotalMinutes);

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The Age ToString() results: {0}", response.Headers.Age.ToString());
        }


        public void DemonstrateHeaderResponseAllow()
        {
            var response = new HttpResponseMessage();

            // Set the header with a string
            response.Headers.Allow.TryParseAdd ("GET");

            // Set the header with a strong type
            response.Headers.Allow.Add(HttpMethod.Patch);

            // Get the strong type out
            foreach (var value in response.Headers.Allow)
            {
                System.Diagnostics.Debug.WriteLine("Allow value: {0}", value.Method);
            }

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The Allow ToString() results: {0}", response.Headers.Allow.ToString());
        }

        public void DemonstrateHeaderResponseCacheControl()
        {
            var response = new HttpResponseMessage();

            // Set the header with a string
            response.Headers.CacheControl.TryParseAdd("public");

            // Set the header with a strong type
            response.Headers.CacheControl.Add(new HttpNameValueHeaderValue("max-age", "30"));

            // Get the strong type out
            foreach (var value in response.Headers.CacheControl)
            {
                System.Diagnostics.Debug.WriteLine("CacheControl {0}={1}", value.Name, value.Value);
            }

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The CacheControl ToString() results: {0}", response.Headers.CacheControl.ToString());
        }

        public void DemonstrateHeaderResponseDate()
        {
            var response = new HttpResponseMessage();

            // Set the header with a strong type.
            response.Headers.Date = DateTimeOffset.UtcNow;

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("Date value in ticks: {0}", response.Headers.Date.Value.Ticks);

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The Date ToString() results: {0}", response.Headers.Date.ToString());
        }

        public void DemonstrateHeaderResponseLocation()
        {
            var response = new HttpResponseMessage();

            // Set the header with a strong type.
            response.Headers.Location = new Uri("http://example.com/");

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("Location absolute uri: {0}", response.Headers.Location.AbsoluteUri);

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The Location ToString() results: {0}", response.Headers.Location.ToString());
        }

        public void DemonstrateHeaderResponseProxyAuthenticate()
        {
            var response = new HttpResponseMessage();

            // Set the header with a strong type.
            response.Headers.ProxyAuthenticate.TryParseAdd("Basic");
            response.Headers.ProxyAuthenticate.Add(new HttpChallengeHeaderValue("authScheme", "authToken"));

            // Get the strong type out
            foreach (var value in response.Headers.ProxyAuthenticate)
            {
                System.Diagnostics.Debug.WriteLine("Proxy authenticate scheme and token: {0} {1}", value.Scheme, value.Token);
            }

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The ProxyAuthenticate ToString() results: {0}", response.Headers.ProxyAuthenticate.ToString());
        }

        public void DemonstrateHeaderResponseRetryAfter()
        {
            var response = new HttpResponseMessage();

            // Set the header with a strong type.
            HttpDateOrDeltaHeaderValue newvalue;
            bool parseOk = HttpDateOrDeltaHeaderValue.TryParse("", out newvalue);
            if (parseOk)
            {
                response.Headers.RetryAfter = newvalue;
            }

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("Date value in ticks: {0}", response.Headers.Date.Value.Ticks);

            // The ToString() is useful for diagnostics, too.
            System.Diagnostics.Debug.WriteLine("The Date ToString() results: {0}", response.Headers.Date.ToString());
        }

Комментарии

HttpResponseHeaderCollection — это коллекция заголовков HTTP, связанных с HTTP-ответом на сообщение HTTP-запроса. Объект HttpResponseHeaderCollection можно использовать для получения или задания определенных заголовков в HTTP-ответе. Большинство свойств объекта HttpResponseHeaderCollection предоставляют доступ к значению определенного заголовка HTTP.

Свойство Headers в HttpResponseMessage возвращает объект HttpResponseHeaderCollection. Так создается httpResponseHeaderCollection.

Перечисление коллекции на C# или Microsoft Visual Basic

Вы можете выполнить итерацию по объекту HttpResponseHeaderCollection в C# или Microsoft Visual Basic. Во многих случаях, например с помощью синтаксиса foreach , компилятор выполняет это приведение за вас, и вам не нужно выполнять приведение IEnumerable явно. Если необходимо выполнить приведение явным образом, например, если вы хотите вызвать GetEnumerator, приведите объект коллекции к IEnumerable<T> с параметром KeyValuePairstring и String в качестве ограничения.

Свойства

Age

Возвращает или задает объект TimeSpan , представляющий значение http-заголовка Age в HTTP-ответе.

Allow

Возвращает httpMethodHeaderValueCollection объектов HttpMethod , представляющих значение заголовка Allow HTTP в HTTP-ответе.

CacheControl

Возвращает httpCacheDirectiveHeaderValueCollection объектов, представляющих значение заголовка HTTP Cache-Control в HTTP-ответе .

Connection

Возвращает httpConnectionOptionHeaderValueCollection объектов HttpConnectionOptionHeaderValue , представляющих значение http-заголовка Подключения в HTTP-ответе.

Date

Возвращает или задает объект DateTime , представляющий значение http-заголовка Date в HTTP-ответе.

Location

Возвращает или задает универсальный код ресурса (URI ), представляющий значение или заголовок HTTP Location в HTTP-ответе.

ProxyAuthenticate

Возвращает httpChallengeHeaderValueCollection объектов HttpChallengeHeaderValue , представляющих значение http-заголовка Proxy-Authenticate в HTTP-ответе .

RetryAfter

Возвращает или задает объект HttpDateOrDeltaHeaderValue , представляющий значение заголовка HTTP Retry-After в HTTP-ответе .

Size

Возвращает количество объектов в httpResponseHeaderCollection.

TransferEncoding

Возвращает httpTransferCodingHeaderValueCollection объектов HttpTransferCodingHeaderValue , представляющих значение http-заголовка Transfer-Encoding в HTTP-ответе .

WwwAuthenticate

Возвращает httpChallengeHeaderValueCollection объектов HttpChallengeHeaderValue , представляющих значение заголовка HTTP WWW-Authenticate в HTTP-ответе .

Методы

Append(String, String)

Добавляет новый элемент в конец httpResponseHeaderCollection.

Clear()

Удаляет все объекты из коллекции.

First()

Извлекает итератор к первому элементу в httpResponseHeaderCollection.

GetView()

Возвращает неизменяемое представление httpResponseHeaderCollection.

HasKey(String)

Определяет, содержит ли httpResponseHeaderCollection указанный ключ.

Insert(String, String)

Вставляет или заменяет элемент в httpResponseHeaderCollection указанным ключом и значением.

Lookup(String)

Поиск элемента в коллекции HttpResponseHeaderCollection.

Remove(String)

Удаляет элемент с заданным ключом из httpResponseHeaderCollection.

ToString()

Возвращает строку, представляющую текущий объект HttpResponseHeaderCollection .

TryAppendWithoutValidation(String, String)

Попробуйте добавить указанный элемент в httpResponseHeaderCollection без проверки.

Применяется к

См. также раздел