Compartir a través de


IHttpResponse::SetHeader (Método)

Establece o anexa el valor de un encabezado de respuesta HTTP especificado.

Sintaxis

virtual HRESULT SetHeader(  
   IN PCSTR pszHeaderName,  
   IN PCSTR pszHeaderValue,  
   IN USHORT cchHeaderValue,  
   IN BOOL fReplace  
) = 0;  
  
virtual HRESULT SetHeader(  
   IN HTTP_HEADER_ID ulHeaderIndex,  
   IN PCSTR pszHeaderValue,  
   IN USHORT cchHeaderValue,  
   IN BOOL fReplace  
) = 0;  

Parámetros

pszHeaderName
[IN] Puntero a una cadena que contiene el nombre del encabezado HTTP que se va a establecer.

ulHeaderIndex
[IN] Identificador de un encabezado HTTP que se va a establecer.

pszHeaderValue
[IN] Puntero a una cadena que contiene el valor del encabezado que se va a establecer.

cchHeaderValue
[IN] Longitud, en caracteres, del valor del encabezado, no incluido el carácter \0.

fReplace
[IN] Especifica si se debe sobrescribir el encabezado existente.

Valor devuelto

Una clase HRESULT. Entre los valores posibles se incluyen los que se indican en la tabla siguiente, entre otros.

Valor Descripción
S_OK Indica que la operación se realizó correctamente.
ERROR_INVALID_DATA Indica que los datos no son válidos (por ejemplo, los datos del encabezado son demasiado largos).
ERROR_INVALID_PARAMETER Indica que el parámetro especificado no es válido (por ejemplo, el parámetro se establece en NULL).
ERROR_NOT_ENOUGH_MEMORY Indica que no hay memoria suficiente para realizar la operación.

Comentarios

El SetHeader método establece el valor de un encabezado HTTP para la respuesta actual. Hay dos versiones sobrecargadas del SetHeader método . La primera permite especificar el encabezado mediante una cadena contenida en el pszHeaderName parámetro . La otra sobrecarga usa un entero largo sin signo que se encuentra en el ulHeaderIndex parámetro .

Nota

No debe usar la sobrecarga que usa el ulHeaderIndex parámetro para establecer el valor del Server encabezado, ya que el valor se anexará al valor de encabezado existente. Use el pszHeaderName parámetro en su lugar.

El nombre de encabezado especificado por el pszHeaderName parámetro puede ser un encabezado personalizado o un encabezado definido en Solicitud de comentarios (RFC) 1945, "Protocolo de transferencia de hipertexto -- HTTP/1.0" o RFC 2616, "Protocolo de transferencia de hipertexto -- HTTP/1.1".

Nota

El pszHeaderName parámetro no puede ser NULL.

El ulHeaderIndex parámetro especifica el identificador de un encabezado HTTP que aparece en la HTTP_HEADER_ID enumeración .

Nota

La HTTP_HEADER_ID enumeración se define en el archivo de encabezado Http.h.

Si el fReplace parámetro es true, el valor de encabezado especificado reemplazará el valor de encabezado existente si el encabezado existe. Si fReplace es false, el valor de encabezado especificado debe anexarse al encabezado existente y separarse del propio encabezado por una coma.

Nota

Otros módulos o controladores pueden llamar al método para reemplazar el SetHeader valor o anexar valores al valor especificado.

Ejemplo

En el ejemplo de código siguiente se muestra cómo usar ambas sobrecargas del SetHeader método para reemplazar los encabezados HTTP Content-Type y Server por valores personalizados y establecer el encabezado HTTP Refresh en un número específico de segundos.

#define _WINSOCKAPI_
#include <windows.h>
#include <sal.h>
#include <httpserv.h>

// Create the module class.
class MyHttpModule : public CHttpModule
{
public:
    REQUEST_NOTIFICATION_STATUS
    OnSendResponse(
        IN IHttpContext * pHttpContext,
        IN ISendResponseProvider * pProvider
    )
    {
        UNREFERENCED_PARAMETER( pProvider );

        // Create an HRESULT to receive return values from methods.
        HRESULT hr;
        
        // Set the "Refresh" header name.
        char szRefreshName[] = "Refresh";
        // Set the "Refresh" header value.
        char szRefreshValue[] = "30";
        // Set the "Content-Type" header value.
        char szContentType[] = "text/plain";
        // Set the "Server" header value.
        char szServerValue[] = "MyServer/7.0";

        // Retrieve a pointer to the response.
        IHttpResponse * pHttpResponse = pHttpContext->GetResponse();

        // Test for an error.
        if (pHttpResponse != NULL)
        {

            // Set the "Refresh" header.
            hr = pHttpResponse->SetHeader(
                szRefreshName,szRefreshValue,
                (USHORT)strlen(szRefreshValue),FALSE);

            // Test for an error.
            if (FAILED(hr))
            {
                // Set the error status.
                pProvider->SetErrorStatus( hr );
                // End additional processing.
                return RQ_NOTIFICATION_FINISH_REQUEST;
            }

            // Set the "Content-Type" header.
            hr = pHttpResponse->SetHeader(
                HttpHeaderContentType,szContentType,
                (USHORT)strlen(szContentType),TRUE);

            // Test for an error.
            if (FAILED(hr))
            {
                // Set the error status.
                pProvider->SetErrorStatus( hr );
                // End additional processing.
                return RQ_NOTIFICATION_FINISH_REQUEST;
            }

            // Set the "Server" header.
            hr = pHttpResponse->SetHeader(
                "Server",szServerValue,
                (USHORT)strlen(szServerValue),TRUE);

            // Test for an error.
            if (FAILED(hr))
            {
                // Set the error status.
                pProvider->SetErrorStatus( hr );
                // End additional processing.
                return RQ_NOTIFICATION_FINISH_REQUEST;
            }
        }
            
        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }
};

// Create the module's class factory.
class MyHttpModuleFactory : public IHttpModuleFactory
{
public:
    HRESULT
    GetHttpModule(
        OUT CHttpModule ** ppModule, 
        IN IModuleAllocator * pAllocator
    )
    {
        UNREFERENCED_PARAMETER( pAllocator );

        // Create a new instance.
        MyHttpModule * pModule = new MyHttpModule;

        // Test for an error.
        if (!pModule)
        {
            // Return an error if the factory cannot create the instance.
            return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
        }
        else
        {
            // Return a pointer to the module.
            *ppModule = pModule;
            pModule = NULL;
            // Return a success status.
            return S_OK;
        }            
    }

    void Terminate()
    {
        // Remove the class from memory.
        delete this;
    }
};

// Create the module's exported registration function.
HRESULT
__stdcall
RegisterModule(
    DWORD dwServerVersion,
    IHttpModuleRegistrationInfo * pModuleInfo,
    IHttpServer * pGlobalInfo
)
{
    UNREFERENCED_PARAMETER( dwServerVersion );
    UNREFERENCED_PARAMETER( pGlobalInfo );

    // Set the request notifications and exit.
    return pModuleInfo->SetRequestNotifications(
        new MyHttpModuleFactory,
        RQ_SEND_RESPONSE,
        0
    );
}

El módulo debe exportar la función RegisterModule . Puede exportar esta función mediante la creación de un archivo de definición de módulo (.def) para el proyecto, o bien puede compilar el módulo mediante el /EXPORT:RegisterModule modificador . Para obtener más información, vea Tutorial: Creación de un módulo HTTP de Request-Level mediante código nativo.

Opcionalmente, puede compilar el código mediante la __stdcall (/Gz) convención de llamada en lugar de declarar explícitamente la convención de llamada para cada función.

Requisitos

Tipo Descripción
Remoto - IIS 7.0 en Windows Vista
- IIS 7.5 en Windows 7
- IIS 8.0 en Windows 8
- IIS 10.0 en Windows 10
Servidor - IIS 7.0 en Windows Server 2008
- IIS 7.5 en Windows Server 2008 R2
- IIS 8.0 en Windows Server 2012
- IIS 8.5 en Windows Server 2012 R2
- IIS 10.0 en Windows Server 2016
Producto - IIS 7.0, IIS 7.5, IIS 8.0, IIS 8.5, IIS 10.0
- IIS Express 7.5, IIS Express 8.0, IIS Express 10.0
Encabezado Httpserv.h

Consulte también

IHttpResponse (Interfaz)
IHttpResponse::D eleteHeader (Método)
IHttpResponse::GetHeader (Método)