Método IHttpServer::GetFileInfo
Retorna uma interface IHttpFileInfo para um caminho de arquivo específico.
Sintaxe
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] Um ponteiro para uma cadeia de caracteres que contém o caminho físico para um arquivo.
hUserToken
[IN] Um HANDLE
que contém o token para o usuário de representação; caso contrário, NULL.
pSid
[IN] Um ponteiro para um SID (identificador de segurança) que contém a ID de segurança para o usuário de representação; caso contrário, NULL.
pszVrPath
[IN] Um ponteiro para uma cadeia de caracteres que contém o caminho virtual a ser registrado para notificações de alteração; caso contrário, NULL.
hVrToken
[IN] Um HANDLE
que contém o token de representação a ser registrado para notificações de alteração; caso contrário, NULL.
fCache
[IN] true
para indicar que o arquivo deve ser armazenado em cache; caso contrário, false
.
ppFileInfo
[OUT] Um ponteiro desreferenciado para uma IHttpFileInfo
interface.
pHttpTraceContext
[IN] Um ponteiro para uma interface IHttpTraceContext opcional.
Valor Retornado
Um HRESULT
. Os possíveis valores incluem, mas sem limitação, aqueles na tabela a seguir.
Valor | Definição |
---|---|
S_OK | Indica que a operação foi bem-sucedida. |
E_FAIL | Indica que a chamada para GetFileInfo foi feita enquanto o host do módulo estava sendo encerrado. |
Comentários
O IHttpServer::GetFileInfo
método cria uma IHttpFileInfo
interface para um caminho específico. Esse método difere do método IHttpContext::GetFileInfo , que retorna uma IHttpFileInfo
interface para o arquivo que o IIS está processando em um contexto de solicitação.
Os pszPhysicalPath
parâmetros e ppFileInfo
são necessários para criar uma IHttpFileInfo
interface. O pszPhysicalPath
parâmetro especifica o caminho para o arquivo e o ppFileInfo
parâmetro define o ponteiro que o IIS preencherá com a interface correspondente IHttpFileInfo
.
Os pszVrPath
parâmetros e hVrToken
são opcionais e você deve defini-los como NULL se você não usá-los. Esses parâmetros especificam, respectivamente, o caminho virtual e o token de representação a serem usados quando um módulo se registra para notificações de alteração (por exemplo, se você solicitar o cache definindo o fCache
parâmetro true
como ).
Observação
Outras definições de configuração podem impedir que o IIS armafique o arquivo em cache, mesmo que você especifique true
para o fCache
parâmetro .
Os hUserToken
parâmetros e pSid
também são opcionais e você deve defini-los como NULL se você não usá-los. Esses parâmetros especificam, respectivamente, o token e o SID para o usuário de representação. O parâmetro opcional restante, pHttpTraceContext
, especifica a IHttpTraceContext
interface para rastreamento.
Exemplo
O exemplo de código a seguir demonstra como criar um módulo HTTP que executa as seguintes tarefas:
Registra-se para a notificação de RQ_BEGIN_REQUEST .
Cria uma classe CHttpModule que contém um método OnBeginRequest . Quando um cliente solicita um arquivo, o
OnBeginRequest
método executa as seguintes tarefas:Mapeia um caminho para uma URL relativa usando o método IHttpContext::MapPath .
Cria uma
IHttpFileInfo
interface para o caminho do arquivo usando oIHttpServer::GetFileInfo
método .Recupera a marca de entidade para o arquivo usando o método IHttpFileInfo::GetETag .
Retorna a marca de entidade para o cliente usando o método IHttpResponse::WriteEntityChunks .
Remove a
CHttpModule
classe da memória e, em seguida, sai.
#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 obter mais informações sobre como criar e implantar um módulo DLL nativo, consulte Passo a passo : criando um módulo HTTP Request-Level usando código nativo.
Opcionalmente, você pode compilar o código usando a __stdcall (/Gz)
convenção de chamada em vez de declarar explicitamente a convenção de chamada para cada função.
Requisitos
Type | Descrição |
---|---|
Cliente | – IIS 7.0 no Windows Vista – IIS 7.5 no Windows 7 – IIS 8.0 no Windows 8 – IIS 10.0 no Windows 10 |
Servidor | – IIS 7.0 no Windows Server 2008 – IIS 7.5 no Windows Server 2008 R2 – IIS 8.0 no Windows Server 2012 – IIS 8.5 no Windows Server 2012 R2 – IIS 10.0 no Windows Server 2016 |
Produto | - 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 |
parâmetro | Httpserv.h |