WebHeaderCollection.Add Método

Definição

Insere um novo cabeçalho na coleção.

Sobrecargas

Add(String)

Insere o cabeçalho especificado na coleção.

Add(HttpRequestHeader, String)

Insere um cabeçalho especificado com o valor especificados na coleção.

Add(HttpResponseHeader, String)

Insere um cabeçalho especificado com o valor especificados na coleção.

Add(String, String)

Insere um cabeçalho com o nome e o valor especificados na coleção.

Add(String)

Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs

Insere o cabeçalho especificado na coleção.

public:
 void Add(System::String ^ header);
public void Add (string header);
override this.Add : string -> unit
Public Sub Add (header As String)

Parâmetros

header
String

O cabeçalho a ser adicionado, com o nome e o valor separados por dois-pontos.

Exceções

header é null ou Empty.

header não contém um caractere de dois-pontos (:).

O tamanho de value é maior que 65535.

- ou -

A parte do nome de header é Empty ou contém caracteres inválidos.

- ou -

header é um cabeçalho restrito que deve ser definido com uma propriedade.

- ou -

A parte do valor de header contém caracteres inválidos.

.NET Framework e NET Core versões 2.0 - 3.1 apenas: o comprimento da cadeia de caracteres após os dois-pontos (:) é maior que 65.535.

Exemplos

O exemplo a seguir adiciona um par nome/valor a um WebHeaderCollection usando o Add Método .

try
{
   //Create a web request for S"www.msn.com".
   HttpWebRequest^ myHttpWebRequest = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.msn.com" ));

   //Get the headers associated with the request.
   WebHeaderCollection^ myWebHeaderCollection = myHttpWebRequest->Headers;
   Console::WriteLine( "Configuring Webrequest to accept Danish and English language using 'Add' method" );

   //Add the Accept-Language header (for Danish) in the request.
   myWebHeaderCollection->Add( "Accept-Language:da" );

   //Include English in the Accept-Langauge header.
   myWebHeaderCollection->Add( "Accept-Language:en;q=0.8" );

   //Get the associated response for the above request.
   HttpWebResponse^ myHttpWebResponse = dynamic_cast<HttpWebResponse^>(myHttpWebRequest->GetResponse());

   //Print the headers for the request.
   printHeaders( myWebHeaderCollection );
   myHttpWebResponse->Close();
}
//Catch exception if trying to add a restricted header.
catch ( ArgumentException^ e ) 
{
   Console::WriteLine( e->Message );
}
catch ( WebException^ e ) 
{
   Console::WriteLine( "\nWebException is thrown. \nMessage is : {0}", e->Message );
   if ( e->Status == WebExceptionStatus::ProtocolError )
   {
      Console::WriteLine( "Status Code : {0}", (dynamic_cast<HttpWebResponse^>(e->Response))->StatusCode );
      Console::WriteLine( "Status Description : {0}", (dynamic_cast<HttpWebResponse^>(e->Response))->StatusDescription );
      Console::WriteLine( "Server : {0}", (dynamic_cast<HttpWebResponse^>(e->Response))->Server );
   }
}
catch ( Exception^ e ) 
{
   Console::WriteLine( "Exception is thrown. Message is : {0}", e->Message );
}
try {
    //Create a web request for "www.msn.com".
    HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

    //Get the headers associated with the request.
    WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

    Console.WriteLine("Configuring Webrequest to accept Danish and English language using 'Add' method");

    //Add the Accept-Language header (for Danish) in the request.
    myWebHeaderCollection.Add("Accept-Language:da");

    //Include English in the Accept-Langauge header. 
    myWebHeaderCollection.Add("Accept-Language","en;q=0.8");

    //Get the associated response for the above request.
    HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

    //Print the headers for the request.
    printHeaders(myWebHeaderCollection);
    myHttpWebResponse.Close();
}
//Catch exception if trying to add a restricted header.
catch(ArgumentException e) {
    Console.WriteLine(e.Message);
}
catch(WebException e) {
    Console.WriteLine("\nWebException is thrown. \nMessage is :" + e.Message);
    if(e.Status == WebExceptionStatus.ProtocolError) {
        Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
        Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
        Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
    }
}
catch(Exception e) {
    Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}
Public Shared Sub Main()

 Try
        'Create a web request for "www.msn.com".
        Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create("http://www.msn.com"), HttpWebRequest)
        
        'Get the headers associated with the request.
        Dim myWebHeaderCollection As WebHeaderCollection = myHttpWebRequest.Headers
        
    Console.WriteLine("Configuring Webrequest to accept Danish and English language using 'Add' method")
        
    'Add the Accept-Language header (for Danish) in the request.
        myWebHeaderCollection.Add("Accept-Language:da")
        
        'Include English in the Accept-Langauge header. 
        myWebHeaderCollection.Add("Accept-Language","en;q" + ChrW(61) + "0.8")
        
        'Get the associated response for the above request.
        Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
        
        'Print the headers for the request.
        printHeaders(myWebHeaderCollection)
        myHttpWebResponse.Close()
    'Catch exception if trying to add a restricted header.
    Catch e As ArgumentException
        Console.WriteLine(e.Message)
    Catch e As WebException
        Console.WriteLine(e.Message)
        If e.Status = WebExceptionStatus.ProtocolError Then
            Console.WriteLine("Status Code : {0}", CType(e.Response, HttpWebResponse).StatusCode)
            Console.WriteLine("Status Description : {0}", CType(e.Response, HttpWebResponse).StatusDescription)
            Console.WriteLine("Server : {0}", CType(e.Response, HttpWebResponse).Server)
        End If
    Catch e As Exception
        Console.WriteLine(e.Message)
    End Try
End Sub

Observação

O comprimento da parte de valor de header, ou seja, a cadeia de caracteres após os dois-pontos (:), é validada apenas nas versões 2.0 e 3.1 do .NET Core e do .NET Framework.

Comentários

O header parâmetro deve ser especificado no formato "name:value". Se o cabeçalho especificado não existir na coleção, um novo cabeçalho será adicionado à coleção.

Se o cabeçalho especificado em header já estiver presente na coleção, a parte do valor será header concatenada com o valor existente.

Aplica-se a

Add(HttpRequestHeader, String)

Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs

Insere um cabeçalho especificado com o valor especificados na coleção.

public:
 void Add(System::Net::HttpRequestHeader header, System::String ^ value);
public void Add (System.Net.HttpRequestHeader header, string? value);
public void Add (System.Net.HttpRequestHeader header, string value);
override this.Add : System.Net.HttpRequestHeader * string -> unit
Public Sub Add (header As HttpRequestHeader, value As String)

Parâmetros

header
HttpRequestHeader

O cabeçalho a ser adicionado à coleção.

value
String

O conteúdo do cabeçalho.

Exceções

.NET Framework e NET Core versões 2.0 - 3.1 apenas: o comprimento de value é maior que 65.535.

Essa instância WebHeaderCollection não permite instâncias de HttpRequestHeader.

Comentários

Se o cabeçalho especificado não existir, o Add método inserirá um novo cabeçalho na lista de pares nome/valor do cabeçalho.

Se o cabeçalho especificado já estiver presente, value será adicionado à lista separada por vírgulas de valores associados ao cabeçalho.

Observação

O comprimento de value é validado apenas em .NET Framework e no .NET Core versões 2.0 - 3.1.

Aplica-se a

Add(HttpResponseHeader, String)

Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs

Insere um cabeçalho especificado com o valor especificados na coleção.

public:
 void Add(System::Net::HttpResponseHeader header, System::String ^ value);
public void Add (System.Net.HttpResponseHeader header, string? value);
public void Add (System.Net.HttpResponseHeader header, string value);
override this.Add : System.Net.HttpResponseHeader * string -> unit
Public Sub Add (header As HttpResponseHeader, value As String)

Parâmetros

header
HttpResponseHeader

O cabeçalho a ser adicionado à coleção.

value
String

O conteúdo do cabeçalho.

Exceções

.NET Framework e NET Core versões 2.0 - 3.1 apenas: o comprimento de value é maior que 65.535.

Essa instância WebHeaderCollection não permite instâncias de HttpResponseHeader.

Comentários

Se o cabeçalho especificado não existir, o Add método inserirá um novo cabeçalho na lista de pares nome/valor do cabeçalho.

Se o cabeçalho especificado já estiver presente, value será adicionado à lista separada por vírgulas de valores associados ao cabeçalho.

Observação

O comprimento de value é validado apenas em .NET Framework e no .NET Core versões 2.0 - 3.1.

Aplica-se a

Add(String, String)

Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs

Insere um cabeçalho com o nome e o valor especificados na coleção.

public:
 override void Add(System::String ^ name, System::String ^ value);
public override void Add (string name, string? value);
public override void Add (string name, string value);
override this.Add : string * string -> unit
Public Overrides Sub Add (name As String, value As String)

Parâmetros

name
String

O cabeçalho a ser adicionado à coleção.

value
String

O conteúdo do cabeçalho.

Exceções

name é null, Empty ou contém caracteres inválidos.

- ou -

name é um cabeçalho restrito que deve ser definido com uma configuração de propriedade.

- ou -

value contém caracteres inválidos.

.NET Framework e NET Core versões 2.0 - 3.1 apenas: o comprimento de value é maior que 65.535.

Exemplos

O exemplo a seguir adiciona um par nome/valor a um WebHeaderCollection usando o Add Método .

try
{
   //Create a web request for S"www.msn.com".
   HttpWebRequest^ myHttpWebRequest = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.msn.com" ));

   //Get the headers associated with the request.
   WebHeaderCollection^ myWebHeaderCollection = myHttpWebRequest->Headers;
   Console::WriteLine( "Configuring Webrequest to accept Danish and English language using 'Add' method" );

   //Add the Accept-Language header (for Danish) in the request.
   myWebHeaderCollection->Add( "Accept-Language:da" );

   //Include English in the Accept-Langauge header.
   myWebHeaderCollection->Add( "Accept-Language:en;q=0.8" );

   //Get the associated response for the above request.
   HttpWebResponse^ myHttpWebResponse = dynamic_cast<HttpWebResponse^>(myHttpWebRequest->GetResponse());

   //Print the headers for the request.
   printHeaders( myWebHeaderCollection );
   myHttpWebResponse->Close();
}
//Catch exception if trying to add a restricted header.
catch ( ArgumentException^ e ) 
{
   Console::WriteLine( e->Message );
}
catch ( WebException^ e ) 
{
   Console::WriteLine( "\nWebException is thrown. \nMessage is : {0}", e->Message );
   if ( e->Status == WebExceptionStatus::ProtocolError )
   {
      Console::WriteLine( "Status Code : {0}", (dynamic_cast<HttpWebResponse^>(e->Response))->StatusCode );
      Console::WriteLine( "Status Description : {0}", (dynamic_cast<HttpWebResponse^>(e->Response))->StatusDescription );
      Console::WriteLine( "Server : {0}", (dynamic_cast<HttpWebResponse^>(e->Response))->Server );
   }
}
catch ( Exception^ e ) 
{
   Console::WriteLine( "Exception is thrown. Message is : {0}", e->Message );
}
try {
    //Create a web request for "www.msn.com".
    HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

    //Get the headers associated with the request.
    WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

    Console.WriteLine("Configuring Webrequest to accept Danish and English language using 'Add' method");

    //Add the Accept-Language header (for Danish) in the request.
    myWebHeaderCollection.Add("Accept-Language:da");

    //Include English in the Accept-Langauge header. 
    myWebHeaderCollection.Add("Accept-Language","en;q=0.8");

    //Get the associated response for the above request.
    HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

    //Print the headers for the request.
    printHeaders(myWebHeaderCollection);
    myHttpWebResponse.Close();
}
//Catch exception if trying to add a restricted header.
catch(ArgumentException e) {
    Console.WriteLine(e.Message);
}
catch(WebException e) {
    Console.WriteLine("\nWebException is thrown. \nMessage is :" + e.Message);
    if(e.Status == WebExceptionStatus.ProtocolError) {
        Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
        Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
        Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
    }
}
catch(Exception e) {
    Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}
Public Shared Sub Main()

 Try
        'Create a web request for "www.msn.com".
        Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create("http://www.msn.com"), HttpWebRequest)
        
        'Get the headers associated with the request.
        Dim myWebHeaderCollection As WebHeaderCollection = myHttpWebRequest.Headers
        
    Console.WriteLine("Configuring Webrequest to accept Danish and English language using 'Add' method")
        
    'Add the Accept-Language header (for Danish) in the request.
        myWebHeaderCollection.Add("Accept-Language:da")
        
        'Include English in the Accept-Langauge header. 
        myWebHeaderCollection.Add("Accept-Language","en;q" + ChrW(61) + "0.8")
        
        'Get the associated response for the above request.
        Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
        
        'Print the headers for the request.
        printHeaders(myWebHeaderCollection)
        myHttpWebResponse.Close()
    'Catch exception if trying to add a restricted header.
    Catch e As ArgumentException
        Console.WriteLine(e.Message)
    Catch e As WebException
        Console.WriteLine(e.Message)
        If e.Status = WebExceptionStatus.ProtocolError Then
            Console.WriteLine("Status Code : {0}", CType(e.Response, HttpWebResponse).StatusCode)
            Console.WriteLine("Status Description : {0}", CType(e.Response, HttpWebResponse).StatusDescription)
            Console.WriteLine("Server : {0}", CType(e.Response, HttpWebResponse).Server)
        End If
    Catch e As Exception
        Console.WriteLine(e.Message)
    End Try
End Sub

Observação

O comprimento de value é validado apenas em .NET Framework e no .NET Core versões 2.0 - 3.1.

Comentários

Se o cabeçalho especificado em name não existir, o Add método inserirá um novo cabeçalho na lista de pares nome/valor do cabeçalho.

Se o cabeçalho especificado em name já estiver presente, value será adicionado à lista separada por vírgulas existente de valores associados namea .

Aplica-se a