Compartir a través de


IHttpServer::GetFileInfo (Método)

Devuelve una interfaz IHttpFileInfo para una ruta de acceso de archivo específica.

Sintaxis

virtual HRESULT GetFileInfo(  
   IN PCWSTR pszPhysicalPath,  
   IN HANDLE hUserToken,  
   IN PSID pSid,  
   IN PCWSTR pszVrPath,  
   IN HANDLE hVrToken,  
   IN BOOL fCache,  
   OUT IHttpFileInfo** ppFileInfo,  
   IN IHttpTraceContext* pHttpTraceContext = NULL  
) = 0;  

Parámetros

pszPhysicalPath
[IN] Puntero a una cadena que contiene la ruta de acceso física a un archivo.

hUserToken
[IN] que HANDLE contiene el token para el usuario de suplantación; en caso contrario, NULL.

pSid
[IN] Puntero a un identificador de seguridad (SID) que contiene el identificador de seguridad para el usuario de suplantación; en caso contrario, NULL.

pszVrPath
[IN] Puntero a una cadena que contiene la ruta de acceso virtual para registrarse para las notificaciones de cambio; en caso contrario, NULL.

hVrToken
[IN] que HANDLE contiene el token de suplantación para registrarse para las notificaciones de cambio; en caso contrario, NULL.

fCache
[IN] true para indicar que el archivo debe almacenarse en caché; de lo contrario, false.

ppFileInfo
[OUT] Puntero desreferenciado a una IHttpFileInfo interfaz.

pHttpTraceContext
[IN] Puntero a una interfaz IHttpTraceContext opcional.

Valor devuelto

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

Value Definición
S_OK Indica que la operación se realizó correctamente.
E_FAIL Indica que la llamada a GetFileInfo se realizó mientras el host del módulo finalizaba.

Comentarios

El IHttpServer::GetFileInfo método crea una IHttpFileInfo interfaz para una ruta de acceso específica. Este método difiere del método IHttpContext::GetFileInfo , que devuelve una IHttpFileInfo interfaz para el archivo que IIS está procesando dentro de un contexto de solicitud.

Los pszPhysicalPath parámetros y ppFileInfo son necesarios para crear una IHttpFileInfo interfaz. El pszPhysicalPath parámetro especifica la ruta de acceso al archivo y el ppFileInfo parámetro define el puntero que IIS rellenará con la interfaz correspondiente IHttpFileInfo .

Los pszVrPath parámetros y hVrToken son opcionales y debe establecerlos en NULL si no los usa. Estos parámetros especifican, respectivamente, la ruta de acceso virtual y el token de suplantación que se usarán cuando un módulo se registre para las notificaciones de cambio (por ejemplo, si solicita el almacenamiento en caché estableciendo el fCache parámetro trueen ).

Nota

Otras opciones de configuración pueden impedir que IIS pueda almacenar en caché el archivo, incluso si se especifica true para el fCache parámetro .

Los hUserToken parámetros y pSid también son opcionales y debe establecerlos en NULL si no los usa. Estos parámetros especifican, respectivamente, el token y el SID para el usuario de suplantación. El parámetro opcional restante, pHttpTraceContext, especifica la interfaz para el IHttpTraceContext seguimiento.

Ejemplo

En el ejemplo de código siguiente se muestra cómo crear un módulo HTTP que realice las tareas siguientes:

  1. Se registra para la notificación de RQ_BEGIN_REQUEST .

  2. Crea una clase CHttpModule que contiene un método OnBeginRequest . Cuando un cliente solicita un archivo, el OnBeginRequest método realiza las siguientes tareas:

    1. Asigna una ruta de acceso a una dirección URL relativa mediante el método IHttpContext::MapPath .

    2. Crea una IHttpFileInfo interfaz para la ruta de acceso del archivo mediante el IHttpServer::GetFileInfo método .

    3. Recupera la etiqueta de entidad del archivo mediante el método IHttpFileInfo::GetETag .

    4. Devuelve la etiqueta de entidad al cliente mediante el método IHttpResponse::WriteEntityChunks .

  3. Quita la CHttpModule clase de la memoria y, a continuación, se cierra.

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

// Create a pointer for the global server interface.
IHttpServer * g_pHttpServer = NULL;

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

        HRESULT hr;

        PWSTR wszUrl = L"/example/default.asp";
        WCHAR wszPhysicalPath[1024] = L"";
        DWORD cbPhysicalPath = 1024;

        pHttpContext->MapPath(wszUrl,wszPhysicalPath,&cbPhysicalPath);

        if (NULL != wszPhysicalPath)
        {
            IHttpFileInfo * pHttpFileInfo;
            hr = g_pHttpServer->GetFileInfo(wszPhysicalPath,
                NULL,NULL,wszUrl,NULL,TRUE,&pHttpFileInfo);
            if (NULL != pHttpFileInfo)
            {
                // Create a buffer for the Etag.
                USHORT cchETag;
                // Retrieve the Etag.
                PCSTR pszETag = pHttpFileInfo->GetETag(&cchETag);
                //Test for an error.
                if (NULL != pszETag)
                {
                    // Clear the existing response.
                    pHttpContext->GetResponse()->Clear();
                    // Set the MIME type to plain text.
                    pHttpContext->GetResponse()->SetHeader(
                        HttpHeaderContentType,"text/plain",
                        (USHORT)strlen("text/plain"),TRUE);
                    // Return the Etag to the client.
                    WriteResponseMessage(pHttpContext,
                        "ETag: ",pszETag);
                    // End additional processing.
                    return RQ_NOTIFICATION_FINISH_REQUEST;
                }
            }
        }

        // Return processing to the pipeline.
        return RQ_NOTIFICATION_CONTINUE;
    }
private:

    // Create a utility method that inserts a name/value pair into the response.
    HRESULT WriteResponseMessage(
        IHttpContext * pHttpContext,
        PCSTR pszName,
        PCSTR pszValue
    )
    {
        // Create an HRESULT to receive return values from methods.
        HRESULT hr;
        
        // Create a data chunk. (Defined in the Http.h file.)
        HTTP_DATA_CHUNK dataChunk;
        // Set the chunk to a chunk in memory.
        dataChunk.DataChunkType = HttpDataChunkFromMemory;
        // Buffer for bytes written of data chunk.
        DWORD cbSent;

        // Set the chunk to the first buffer.
        dataChunk.FromMemory.pBuffer =
            (PVOID) pszName;
        // Set the chunk size to the first buffer size.
        dataChunk.FromMemory.BufferLength =
            (USHORT) strlen(pszName);
        // Insert the data chunk into the response.
        hr = pHttpContext->GetResponse()->WriteEntityChunks(
            &dataChunk,1,FALSE,TRUE,&cbSent);
        // Test for an error.
        if (FAILED(hr))
        {
            // Return the error status.
            return hr;
        }

        // Set the chunk to the second buffer.
        dataChunk.FromMemory.pBuffer =
            (PVOID) pszValue;
        // Set the chunk size to the second buffer size.
        dataChunk.FromMemory.BufferLength =
            (USHORT) strlen(pszValue);
        // Insert the data chunk into the response.
        hr = pHttpContext->GetResponse()->WriteEntityChunks(
            &dataChunk,1,FALSE,TRUE,&cbSent);
        // Test for an error.
        if (FAILED(hr))
        {
            // Return the error status.
            return hr;
        }

        // Return a success status.
        return S_OK;
    }
};

// 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 );

    // Store the pointer for the global server interface.
    g_pHttpServer = pGlobalInfo;

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

Para obtener más información sobre cómo crear e implementar un módulo DLL nativo, consulte 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

IHttpServer (interfaz)
IHttpContext::GetFileInfo (Método)