WebHeaderCollection.Add Método

Definição

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

Sobrecargas

Name Description
Add(String)

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

Add(HttpRequestHeader, String)

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

Add(HttpResponseHeader, String)

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

Add(String, String)

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

Add(String)

Origem:
WebHeaderCollection.cs
Origem:
WebHeaderCollection.cs
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 adicionar, com o nome e o valor separados por dois pontos.

Exceções

header é null ou Empty.

header não contém dois pontos (carácter:).

-ou-

A duração da parte de valor de header é superior a 65535.

-ou-

A parte do nome é headerEmpty ou contém caracteres inválidos.

-ou-

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

-ou-

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

.NET Framework e .NET Core versões 2.0 - 3.1 apenas: O comprimento da cadeia após os dois pontos (:) é superior a 65535.

Exemplos

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

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

Note

O comprimento da porção valor de header, ou seja, a cadeia após o dois-pontos (:), é validada apenas no .NET Framework e .NET versões Core 2.0 - 3.1.

Observações

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

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

Aplica-se a

Add(HttpRequestHeader, String)

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

Insere o cabeçalho especificado com o valor especificado 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 para adicionar à 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 é superior a 65535.

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

Observações

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

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

Note

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

Aplica-se a

Add(HttpResponseHeader, String)

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

Insere o cabeçalho especificado com o valor especificado 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 para adicionar à 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 é superior a 65535.

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

Observações

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

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

Note

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

Aplica-se a

Add(String, String)

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

Insere um cabeçalho com o nome e 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 para adicionar à 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 é superior a 65535.

Exemplos

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

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

Note

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

Observações

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

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

Aplica-se a