HttpRequestHeaderCollection 类

定义

提供与 HTTP 请求关联的 HTTP 标头的集合。

public ref class HttpRequestHeaderCollection 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 HttpRequestHeaderCollection 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 HttpRequestHeaderCollection 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 HttpRequestHeaderCollection : 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 HttpRequestHeaderCollection : IDictionary<string,string>, IEnumerable<KeyValuePair<string,string>>, IStringable
Public NotInheritable Class HttpRequestHeaderCollection
Implements IDictionary(Of String, String), IEnumerable(Of KeyValuePair(Of String, String)), IStringable
继承
Object Platform::Object IInspectable HttpRequestHeaderCollection
属性
实现
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 中引入)

示例

下面的示例代码演示了一个方法,该方法使用 HttpRequestHeaderCollection 对象的属性获取和设置 HttpRequestMessage 对象上的请求标头。 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;

        public void DemonstrateHeaderRequest()
        {
            DemonstrateHeaderRequestAccept();
            DemonstrateHeaderRequestAcceptEncoding();
            DemonstrateHeaderRequestAcceptLanguage();
            DemonstrateHeaderRequestAuthorization();
            DemonstrateHeaderRequestCacheControl();
            DemonstrateHeaderRequestConnection();
            DemonstrateHeaderRequestCookie();
            DemonstrateHeaderRequestDate();
            DemonstrateHeaderRequestFrom();
            DemonstrateHeaderRequestHost();
            DemonstrateHeaderRequestIfModifiedSince();
            DemonstrateHeaderRequestIfUnmodifiedSince();
            DemonstrateHeaderRequestMaxForwards();
            DemonstrateHeaderRequestProxyAuthorization();
            DemonstrateHeaderRequestReferer();
            DemonstrateHeaderRequestUserAgent();
        }

        public void DemonstrateHeaderRequestAccept()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.Accept.TryParseAdd ("audio/*");
            parsedOk = request.Headers.Accept.TryParseAdd ("audio/*; q=0.2");
            parsedOk = request.Headers.Accept.TryParseAdd ("audio/*; q=0.4; mysetting=myvalue");

            // Set the header with a strong type.
            request.Headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("audio/*", .6));

            // Get the strong type out
            foreach (var value in request.Headers.Accept)
            {
                System.Diagnostics.Debug.WriteLine("One of the Accept values: {0}={1}", value.MediaType, value.Quality);
            }

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

        public void DemonstrateHeaderRequestAcceptEncoding()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.AcceptEncoding.TryParseAdd("compress");
            parsedOk = request.Headers.AcceptEncoding.TryParseAdd("gzip;q=1.0");

            // Set the header with a strong type.
            request.Headers.AcceptEncoding.Add(new HttpContentCodingWithQualityHeaderValue("*", 0));

            // Get the strong type out
            foreach (var value in request.Headers.AcceptEncoding)
            {
                System.Diagnostics.Debug.WriteLine("One of the AcceptEncoding values: {0}={1}", value.ContentCoding, value.Quality);
            }

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

        public void DemonstrateHeaderRequestAcceptLanguage()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.AcceptLanguage.TryParseAdd("da");
            parsedOk = request.Headers.AcceptLanguage.TryParseAdd("en-gb;q=0.8");

            // Set the header with a strong type.
            request.Headers.AcceptLanguage.Add(new HttpLanguageRangeWithQualityHeaderValue("en", .7));

            // Get the strong type out
            foreach (var value in request.Headers.AcceptLanguage)
            {
                System.Diagnostics.Debug.WriteLine("One of the AcceptLanguage values: {0}={1}", value.LanguageRange, value.Quality);
            }

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

        public void DemonstrateHeaderRequestAuthorization()
        {
            var request = new HttpRequestMessage();

            // Set the header with a strong type.
            string username = "user";
            string password = "password";
            var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary (username + ":" + password, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            string base64token = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);
            request.Headers.Authorization = new HttpCredentialsHeaderValue("Basic", base64token);


            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("One of the Authorization values: {0}={1}", 
                request.Headers.Authorization.Scheme,
                request.Headers.Authorization.Token);

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

        public void DemonstrateHeaderRequestCacheControl()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.CacheControl.TryParseAdd("no-store");

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

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

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


        public void DemonstrateHeaderRequestConnection()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.Connection.TryParseAdd("close");

            // Set the header with a strong type.
            request.Headers.Connection.Add(new HttpConnectionOptionHeaderValue("cache-control"));

            // Get the strong type out
            foreach (var value in request.Headers.Connection)
            {
                System.Diagnostics.Debug.WriteLine("One of the Connection values: {0}", value.Token);
            }

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

        public void DemonstrateHeaderRequestCookie()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.Cookie.TryParseAdd("cookieName=cookieValue");

            // Set the header with a strong type.
            request.Headers.Cookie.Add(new HttpCookiePairHeaderValue("cookie2", "value2"));

            // Get the strong type out
            foreach (var value in request.Headers.Cookie)
            {
                System.Diagnostics.Debug.WriteLine("One of the Cookie values: {0}={1}", value.Name, value.Value);
            }

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


        public void DemonstrateHeaderRequestDate()
        {
            var request = new HttpRequestMessage();

            // This is not typically set with a string.

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

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

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

        public void DemonstrateHeaderRequestFrom()
        {
            var request = new HttpRequestMessage();

            // Set the header with a string.
            request.Headers.From = "person@example.com";

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("From value: {0}", request.Headers.From);
        }

        public void DemonstrateHeaderRequestHost()
        {
            var request = new HttpRequestMessage();

            // This is not typically set with a string.

            // Set the header with a strong type.
            // HostName is in the Windows.Networking namespace.
            var value = new Windows.Networking.HostName("example.com");
            request.Headers.Host = value;

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("Canonical Host name: {0}", request.Headers.Host.CanonicalName);

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

        public void DemonstrateHeaderRequestIfModifiedSince()
        {
            var request = new HttpRequestMessage();

            // This is not typically set with a string.

            // Set the header with a strong type.
            var value = DateTimeOffset.Now.AddDays(-1); // Since yesterday.
            request.Headers.IfModifiedSince = value;

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

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

        public void DemonstrateHeaderRequestIfUnmodifiedSince()
        {
            var request = new HttpRequestMessage();

            // This is not typically set with a string.

            // Set the header with a strong type.
            var value = DateTimeOffset.Now.AddDays(-1); // Since yesterday.
            request.Headers.IfUnmodifiedSince = value;

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

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

        public void DemonstrateHeaderRequestMaxForwards()
        {
            var request = new HttpRequestMessage();

            // Set the header with an integer.
            request.Headers.MaxForwards= 2;

            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("MaxForwards value: {0}", request.Headers.MaxForwards);
        }

        public void DemonstrateHeaderRequestProxyAuthorization()
        {
            var request = new HttpRequestMessage();

            // Set the header with a strong type.
            string username = "user";
            string password = "password";
            var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(username + ":" + password, Windows.Security.Cryptography.BinaryStringEncoding.Utf16LE);
            string base64token = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);
            request.Headers.ProxyAuthorization = new HttpCredentialsHeaderValue("Basic", base64token);


            // Get the strong type out
            System.Diagnostics.Debug.WriteLine("One of the ProxyAuthorixation values: {0}={1}",
                request.Headers.ProxyAuthorization.Scheme,
                request.Headers.ProxyAuthorization.Token);

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


        public void DemonstrateHeaderRequestReferer()
        {
            var request = new HttpRequestMessage();

            // This is not typically set with a string.

            // Set the header with a strong type.
            // Uri is either in the Windows.Foundation namespace (JavaScript and C++)
            // or in the System.Net namespace (C#).
            var value = new Uri("http://example.com/");
            request.Headers.Referer = value;

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

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

        public void DemonstrateHeaderRequestUserAgent()
        {
            var request = new HttpRequestMessage();
            bool parsedOk = false;

            // Set the header with a string.
            parsedOk = request.Headers.UserAgent.TryParseAdd("testprogram/1.0");

            // Set the header with a strong type.
            request.Headers.UserAgent.Add(new HttpProductInfoHeaderValue("myprogram", "2.2"));

            // Get the strong type out
            foreach (var value in request.Headers.UserAgent)
            {
                System.Diagnostics.Debug.WriteLine("One of the UserAgent values: {0} / {1}", value.Product.Name, value.Product.Version);
            }

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

注解

HttpRequestHeaderCollection 是与 HTTP 请求关联的 HTTP 标头的集合。 HttpRequestHeaderCollection 对象可用于获取或设置 HTTP 请求上的特定标头。 HttpRequestHeaderCollection 对象上的大多数属性都提供对特定 HTTP 标头值的访问权限。

HttpRequestMessage 上的 Headers 属性返回 HttpRequestHeaderCollection 对象。 HttpClient 上的 DefaultRequestHeaders 属性还返回 HttpRequestHeaderCollection 对象。 这两种方法用于构造 HttpRequestHeaderCollection 对象。

HttpRequestHeaderCollection 表示应用开发人员可以设置的 HTTP 请求上的 HTTP 标头,而不是最终可能随请求一起发送的所有标头。 HttpBaseProtocolFilter 将添加一些附加标头。

基础堆栈可以更改 HTTP 请求上的标头。 这就是应用可能需要在请求完成后从 HttpRequestHeaderCollection 获取标头值的原因。

枚举 C# 或 Microsoft Visual Basic 中的集合

可以在 C# 或 Microsoft Visual Basic 中循环访问 HttpRequestHeaderCollection 对象。 在许多情况下,例如使用 foreach 语法,编译器会为你执行此强制转换,你无需显式转换为 IEnumerable 。 如果需要显式强制转换(例如,如果要调用 GetEnumerator),请将集合对象强制转换为 IEnumerable<T> ,其 KeyValuePairStringString 作为约束。

属性

Accept

获取 HttpMediaTypeWithQualityHeaderValue 对象的 HttpMediaTypeWithQualityHeaderValueCollection ,该对象表示 HTTP 请求上的 Accept HTTP 标头的值。

AcceptEncoding

获取 HttpContentCodingWithQualityHeaderValue 对象的 HttpContentCodingWithQualityHeaderValueCollection ,这些对象表示 HTTP 请求上的 Accept-Encoding HTTP 标头的值。

AcceptLanguage

获取 HttpLanguageRangeWithQualityHeaderValue 对象的 HttpLanguageRangeWithQualityHeaderValueCollection ,该对象表示 HTTP 请求中 Accept-Language HTTP 标头的值。

Authorization

获取或设置 HttpCredentialsHeaderValue 对象,该对象表示 HTTP 请求上的 授权 HTTP 标头的值。

CacheControl

获取 HttpCacheDirectiveHeaderValueCollection ,它表示 HTTP 请求上的 Cache-Control HTTP 标头的值。

Connection

获取 HttpConnectionOptionHeaderValue 对象的 HttpConnectionOptionHeaderValueCollection ,这些对象表示 HTTP 请求上的 Connection HTTP 标头的值。

Cookie

获取 HttpCookiePairHeaderValue 对象的 HttpCookiePairHeaderValueCollection ,这些对象表示在 HTTP 请求中发送的 Cookie HTTP 标头的值。

Date

获取或设置 DateTime 对象,该对象表示 HTTP 请求上的 Date HTTP 标头的值。

Expect

获取 HttpExpectationHeaderValue 对象的 HttpExpectationHeaderValueCollection ,这些对象表示 HTTP 请求上的 Expect HTTP 标头的值。

From

获取或设置 字符串 ,表示 HTTP 请求上的 From HTTP 标头的值。

Host

获取或设置 HostName ,该名称表示 HTTP 请求上的 主机 HTTP 标头的值。

IfModifiedSince

获取或设置 DateTime 对象,该对象代表 HTTP 请求中 If-Modified-Since HTTP 标头的值。

IfUnmodifiedSince

获取或设置 DateTime 对象,该对象代表 HTTP 请求上的 If-Unmodified-Since HTTP 标头的值。

MaxForwards

获取或设置一个整数值,该值代表 HTTP 请求中 Max-Forwards HTTP 标头的值。

ProxyAuthorization

获取或设置 HttpCredentialsHeaderValue 对象,该对象表示 HTTP 请求上的 代理授权 HTTP 标头的值。

Referer

获取或设置 URI,该 URI 表示 HTTP 请求中的 引用器 HTTP 标头的值。

Size

获取 HttpRequestHeaderCollection 中的对象数。

TransferEncoding

获取 HttpTransferCodingHeaderValue 对象的 HttpTransferCodingHeaderValueCollection ,这些对象表示 HTTP 请求上的 Transfer-Encoding HTTP 标头的值。

UserAgent

获取 HttpProductInfoHeaderValue 对象的 HttpProductInfoHeaderValueCollection ,这些对象表示 HTTP 请求中 用户代理 HTTP 标头的值。

方法

Append(String, String)

将新项添加到 HttpRequestHeaderCollection 的末尾。

Clear()

HttpRequestHeaderCollection 中删除所有对象。

First()

检索 HttpRequestHeaderCollection 中第一项的迭代器。

GetView()

返回 HttpRequestHeaderCollection 的不可变视图。

HasKey(String)

确定 HttpRequestHeaderCollection 是否包含指定的键。

Insert(String, String)

使用指定的键和值插入或替换 HttpRequestHeaderCollection 中的项。

Lookup(String)

HttpRequestHeaderCollection 中查找项(如果存在)。

Remove(String)

HttpRequestHeaderCollection 中删除特定对象。

ToString()

返回表示当前 HttpRequestHeaderCollection 对象的字符串。

TryAppendWithoutValidation(String, String)

尝试在没有验证的情况下将指定项追加到 HttpRequestHeaderCollection

适用于

另请参阅