Share via


HttpResponseHeaderCollection Clase

Definición

Proporciona una colección de los encabezados HTTP asociados a una respuesta 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
Herencia
Object Platform::Object IInspectable HttpResponseHeaderCollection
Atributos
Implementaciones
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 de Windows

Familia de dispositivos
Windows 10 (se introdujo en la versión 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (se introdujo en la versión v1.0)

Ejemplos

El código de ejemplo siguiente muestra un método para obtener y establecer encabezados de respuesta en un objeto HttpResponseMessage mediante las propiedades del objeto HttpResponseHeaderCollection. El espacio de nombres Windows.Web.Http.Headers tiene una serie de clases de colección de encabezados fuertemente tipadas y de valor para encabezados HTTP específicos que se pueden usar para obtener y establecer encabezados con validación.

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

Comentarios

HttpResponseHeaderCollection es una colección de los encabezados HTTP asociados a una respuesta HTTP a un mensaje de solicitud HTTP. El objeto HttpResponseHeaderCollection se puede usar para obtener o establecer los encabezados específicos en la respuesta HTTP. La mayoría de las propiedades del objeto HttpResponseHeaderCollection proporcionan acceso al valor de un encabezado HTTP específico.

La propiedad Headers de HttpResponseMessage devuelve un objeto HttpResponseHeaderCollection. Así es como se construye una clase HttpResponseHeaderCollection.

Enumeración de la colección en C# o Microsoft Visual Basic

Puede recorrer en iteración un objeto HttpResponseHeaderCollection en C# o Microsoft Visual Basic. En muchos casos, como el uso de la sintaxis foreach , el compilador realiza esta conversión por usted y no tendrá que convertir a IEnumerable explícitamente. Si necesita convertir explícitamente, por ejemplo, si desea llamar a GetEnumerator, convierta el objeto de colección en IEnumerable<T> con un KeyValuePair de String y String como restricción.

Propiedades

Age

Obtiene o establece el objeto TimeSpan que representa el valor de un encabezado HTTP Age en una respuesta HTTP.

Allow

Obtiene la httpMethodHeaderValueCollection de objetos HttpMethod que representan el valor de un encabezado HTTP Allow en una respuesta HTTP.

CacheControl

Obtiene la httpCacheDirectiveHeaderValueCollection de objetos que representan el valor de un encabezado HTTP Cache-Control en una respuesta HTTP.

Connection

Obtiene la httpConnectionOptionHeaderValueCollection de los objetos HttpConnectionOptionHeaderValue que representan el valor de un encabezado HTTP de conexión en una respuesta HTTP.

Date

Obtiene o establece el objeto DateTime que representa el valor de un encabezado HTTP date en una respuesta HTTP.

Location

Obtiene o establece el URI que representa el valor o un encabezado HTTP de ubicación en una respuesta HTTP.

ProxyAuthenticate

Obtiene la httpChallengeHeaderValueCollection de objetos HttpChallengeHeaderValue que representan el valor de un encabezado HTTP Proxy-Authenticate en una respuesta HTTP.

RetryAfter

Obtiene o establece el objeto HttpDateOrDeltaHeaderValue que representa el valor de un encabezado HTTP Retry-After en una respuesta HTTP.

Size

Obtiene el número de objetos de httpResponseHeaderCollection.

TransferEncoding

Obtiene la httpTransferCodingHeaderValueCollection de los objetos HttpTransferCodingHeaderValue que representan el valor de un encabezado HTTP Transfer-Encoding en una respuesta HTTP.

WwwAuthenticate

Obtiene la httpChallengeHeaderValueCollection de objetos HttpChallengeHeaderValue que representan el valor de un encabezado HTTP WWW-Authenticate en una respuesta HTTP.

Métodos

Append(String, String)

Agrega un nuevo elemento al final de httpResponseHeaderCollection.

Clear()

Quita todos los objetos de la colección.

First()

Recupera un iterador en el primer elemento de httpResponseHeaderCollection.

GetView()

Devuelve una vista inmutable de HttpResponseHeaderCollection.

HasKey(String)

Determina si HttpResponseHeaderCollection contiene la clave especificada.

Insert(String, String)

Inserta o reemplaza un elemento en HttpResponseHeaderCollection por la clave y el valor especificados.

Lookup(String)

Busque un elemento en httpResponseHeaderCollection.

Remove(String)

Quita un elemento con una clave determinada de httpResponseHeaderCollection.

ToString()

Devuelve una cadena que representa el objeto HttpResponseHeaderCollection actual.

TryAppendWithoutValidation(String, String)

Intente anexar el elemento especificado a HttpResponseHeaderCollection sin validación.

Se aplica a

Consulte también