HttpResponseHeaderCollection Classe

Definição

Fornece uma coleção dos cabeçalhos HTTP associados a uma resposta 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
Herança
Object Platform::Object IInspectable HttpResponseHeaderCollection
Atributos
Implementações
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

Requisitos do Windows

Família de dispositivos
Windows 10 (introduzida na 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduzida na v1.0)

Exemplos

O código de exemplo a seguir mostra um método para obter e definir cabeçalhos de resposta em um objeto HttpResponseMessage usando as propriedades no objeto HttpResponseHeaderCollection. O namespace Windows.Web.Http.Headers tem várias classes de valor e coleção de cabeçalhos fortemente tipada para cabeçalhos HTTP específicos que podem ser usados para obter e definir cabeçalhos com validação.

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());
        }

Comentários

O HttpResponseHeaderCollection é uma coleção dos cabeçalhos HTTP associados a uma resposta HTTP a uma mensagem de solicitação HTTP. O objeto HttpResponseHeaderCollection pode ser usado para obter ou definir os cabeçalhos específicos na resposta HTTP. A maioria das propriedades no objeto HttpResponseHeaderCollection fornece acesso para o valor de um cabeçalho HTTP específico.

A propriedade Headers em HttpResponseMessage retorna um objeto HttpResponseHeaderCollection. É assim que um HttpResponseHeaderCollection é construído.

Enumerando a coleção em C# ou Microsoft Visual Basic

Você pode iterar por meio de um objeto HttpResponseHeaderCollection em C# ou Microsoft Visual Basic. Em muitos casos, como o uso da sintaxe foreach , o compilador faz essa conversão para você e você não precisará converter IEnumerable explicitamente. Se você precisar converter explicitamente, por exemplo, se quiser chamar GetEnumerator, converta o objeto de coleção para IEnumerable<T> com um KeyValuePair de String e String como a restrição.

Propriedades

Age

Obtém ou define o objeto TimeSpan que representa o valor de um cabeçalho HTTP Age em uma resposta HTTP.

Allow

Obtém o HttpMethodHeaderValueCollection de objetos HttpMethod que representam o valor de um cabeçalho Permitir HTTP em uma resposta HTTP.

CacheControl

Obtém o HttpCacheDirectiveHeaderValueCollection de objetos que representam o valor de um cabeçalho HTTP cache-control em uma resposta HTTP.

Connection

Obtém os objetos HttpConnectionOptionHeaderValueCollection de objetos HttpConnectionOptionHeaderValue que representam o valor de um cabeçalho HTTP connection em uma resposta HTTP.

Date

Obtém ou define o objeto DateTime que representa o valor de um cabeçalho HTTP Date em uma resposta HTTP.

Location

Obtém ou define o Uri que representa o valor ou um cabeçalho HTTP local em uma resposta HTTP.

ProxyAuthenticate

Obtém os objetos HttpChallengeHeaderValueCollection de objetos HttpChallengeHeaderValue que representam o valor de um cabeçalho HTTP Proxy-Authenticate em uma resposta HTTP.

RetryAfter

Obtém ou define o objeto HttpDateOrDeltaHeaderValue que representa o valor de um cabeçalho HTTP Retry-After em uma resposta HTTP.

Size

Obtém o número de objetos no HttpResponseHeaderCollection.

TransferEncoding

Obtém os objetos HttpTransferCodingHeaderValueCollection de objetos HttpTransferCodingHeaderValue que representam o valor de um cabeçalho HTTP Transfer-Encoding em uma resposta HTTP.

WwwAuthenticate

Obtém os objetos HttpChallengeHeaderValueCollection de objetos HttpChallengeHeaderValue que representam o valor de um cabeçalho HTTP WWW-Authenticate em uma resposta HTTP.

Métodos

Append(String, String)

Adiciona um novo item ao final do HttpResponseHeaderCollection.

Clear()

Remove todos os objetos da coleção.

First()

Recupera um iterador para o primeiro item no HttpResponseHeaderCollection.

GetView()

Retorna uma exibição imutável do HttpResponseHeaderCollection.

HasKey(String)

Determina se HttpResponseHeaderCollection contém a chave especificada.

Insert(String, String)

Insere ou substitui um item no HttpResponseHeaderCollection pela chave e o valor especificados.

Lookup(String)

Pesquise um item no HttpResponseHeaderCollection.

Remove(String)

Remove um item com uma determinada chave do HttpResponseHeaderCollection.

ToString()

Retorna uma cadeia de caracteres que representa o objeto HttpResponseHeaderCollection atual.

TryAppendWithoutValidation(String, String)

Tente acrescentar o item especificado ao HttpResponseHeaderCollection sem validação.

Aplica-se a

Confira também