Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
Este tópico ainda não foi avaliado como - Avalie este tópico

VirtualPathProvider Classe

Fornece um conjunto de métodos que permitem um aplicativo da Web para recuperar os recursos de um sistema de arquivos virtual.

Namespace:  System.Web.Hosting
Assembly:  System.Web (em System.Web. dll)

[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Medium)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.High)]
public abstract class VirtualPathProvider : MarshalByRefObject

The VirtualPathProvider class provides a set of methods for implementing a virtual file system for a Web application.Em um sistema de arquivos virtual, os arquivos e diretórios são gerenciados por um armazenamento de dados diferentes que o sistema de arquivos fornecido pelo sistema operacional do servidor.For example, you can use a virtual file Sistema to store Conteúdo in a SQL Servidor database.

Você pode armazenar qualquer arquivo que é processado na Solicitar em um sistema de arquivos virtual.Isso inclui:

  • Páginas ASP.NET, as páginas mestras, controles de usuário e outros objetos.

  • Páginas da Web padrão com extensões, como .htm e JPG.

  • Any custom extension mapped to a BuildProvider instance.

  • Any named theme in the App_Theme folder.

Você Não Pode Armazenar Pastas do Aplicativo ASP.NET ou arquivos que geram conjuntos de módulos (assemblies) no nível do aplicativo em um sistema de arquivos virtual.Isso inclui:

  • O Global. Arquivo ASAX.

  • Arquivos Web.config.

  • Site map data files used by the XmlSiteMapProvider.

  • Diretórios que contêm os conjuntos de módulos do aplicativo ou que geram conjuntos de módulos (assemblies) do aplicativo: Bin, App_Code, App_GlobalResources, any App_LocalResources.

  • The application data folder, App_Data.

Observação:

If a Web site is precompiled for deployment, content provided by a VirtualPathProvider instance is not compiled, and no VirtualPathProvider instances are used by the precompiled site.

Registrando um VirtualPathProvider

A custom VirtualPathProvider instance should be registered with the ASP.NET compilation system by using the HostingEnvironment.RegisterVirtualPathProvider method before any page parsing or compilation is performed by the Web application.

Typically, a VirtualPathProvider instance is registered in an AppInitialize method defined in the App_Code directory, or during the Application_Start event in the Global.asax file.For an example of registering a VirtualPathProvider instance in an AppInitialize method, see the Example section.

You can register a VirtualPathProvider instance during other events, but pages compiled and cached before the VirtualPathProvider instance is registered will not be invalidated, even if the new VirtualPathProvider instance would now provide the source for the previously compiled page.

OBSERVAÇÕES PARA Inheritors:

When you inherit from VirtualPathProvider, you must override the following members:

If your custom VirtualPathProvider class supports directories in the virtual file system, you must override the following members.

Observação:

If your virtual file system will contain themes for the Web site (by creating a virtual App_Themes directory), your custom VirtualPathProvider class must support directories.

A custom VirtualPathProvider class works with classes derived from the VirtualFile and VirtualDirectory classes.Você deve implementar as classes derivadas desses tipos para fornecer informações de arquivos e diretórios do sistema de arquivos virtual.For an example of a custom VirtualFile implementation, see the Example section of the VirtualFile class overview topic.For an example of a custom VirtualDirectory implementation, see the Example section of the VirtualDirectory class overview topic.

The following code example is a VirtualPathProvider class implementation that creates a virtual file system using information stored in a DataSet object.The code example works with the code examples for the VirtualFile and VirtualDirectory classes to provide virtual resources from a data store that is loaded into a DataSet object.

Este exemplo tem quatro partes: the VirtualPathProvider class implementation, an XML data file used to populate the DataSet object, an AppStart object that contains an AppInitialize method used to register the VirtualPathProvider class with the compilation system, and an ASP.NET page that provides links to the virtual files.

Para usar este código de exemplo em um aplicativo, execute essas etapas.

  1. Criar Um aplicativo exemplo no seu servidor Web.

  2. Copy the source code for the custom VirtualPathProvider object (see below) into a file in the application's App_Code directory.

  3. Copy the source code for the custom VirtualDirectory object (see the Example section in the VirtualDirectory class overview topic) into a file in the application's App_Code directory.

  4. Copy the source code for the custom VirtualFile object (see the Example section in the VirtualFile class overview topic) into a file in the application's App_Code directory.

  5. Copy the source code for the AppStart object (see below) into a file in the application's App_Code directory.

  6. Copy the XML data (see below) into a file named XMLData.xml into a file in the application's App_Data directory.

  7. Copy the default.aspx file (see below) into the root directory of the sample application.Use a Web browser to open the default.aspx file, and then click the links on the page to see the contents of the virtual files.

The first example is a custom VirtualPathProvider class.The DirectoryExists and FileExists methods are overridden to indicate whether a requested directory is present in the virtual file system.The GetDirectory and GetFile methods are overridden to return custom VirtualDirectory and VirtualFile instances containing information from the virtual file system.

The class also provides a GetVirtualData method used by the VirtualDirectory and VirtualFile classes to access the DataSet object containing the virtual file system data.Em uma implementação de produção, este método geralmente seria ser implementado em um objeto comercial responsável por interagir com o armazenamento de dados.

 System;
 System.Data;
 System.Security.Permissions;
 System.Web;
 System.Web.Caching;
 System.Web.Hosting;

 Samples.AspNet.CS
{
  [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.High)]
    SamplePathProvider : VirtualPathProvider
  {
     string dataFile;

     SamplePathProvider()
      : ()
    {
    }

       Initialize()
    {
      
      dataFile = HostingEnvironment.ApplicationPhysicalPath + ;
    }

    
    
    
    
    
    
    
    
    
    
     DataSet GetVirtualData()
    {
      
      DataSet ds = (DataSet)HostingEnvironment.Cache.Get();
       (ds == )
      {
        
        ds =  DataSet();
        ds.ReadXml(dataFile);

        
        CacheDependency cd =  CacheDependency(dataFile);

        
        HostingEnvironment.Cache.Add(, ds, cd,
          Cache.NoAbsoluteExpiration,
           TimeSpan(0, 20, 0),
          CacheItemPriority.Default, );

        
        DateTime dataTimeStamp = DateTime.Now;
        
        HostingEnvironment.Cache.Insert(, dataTimeStamp, ,
          Cache.NoAbsoluteExpiration,
           TimeSpan(0, 20, 0),
          CacheItemPriority.Default, );
      }
       ds;
    }

    
    
    
    
    
    
    
    
    
      IsPathVirtual(string virtualPath)
    {
      String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
       checkPath.StartsWith(, StringComparison.InvariantCultureIgnoreCase);
    }

       FileExists(string virtualPath)
    {
       (IsPathVirtual(virtualPath))
      {
        SampleVirtualFile file = (SampleVirtualFile)GetFile(virtualPath);
         file.Exists;
      }
      
         Previous.FileExists(virtualPath);
    }

       DirectoryExists(string virtualDir)
    {
       (IsPathVirtual(virtualDir))
      {
        SampleVirtualDirectory dir = (SampleVirtualDirectory)GetDirectory(virtualDir);
         dir.Exists;
      }
      
         Previous.DirectoryExists(virtualDir);
    }

      VirtualFile GetFile(string virtualPath)
    {
       (IsPathVirtual(virtualPath))
          SampleVirtualFile(virtualPath, );
      
         Previous.GetFile(virtualPath);
    }

      VirtualDirectory GetDirectory(string virtualDir)
    {
       (IsPathVirtual(virtualDir))
          SampleVirtualDirectory(virtualDir, );
      
         Previous.GetDirectory(virtualDir);
    }

      CacheDependency GetCacheDependency(
      string virtualPath, 
      System.Collections.IEnumerable virtualPathDependencies, 
      DateTime utcStart)
    {
       (IsPathVirtual(virtualPath))
      {
        System.Collections.Specialized.StringCollection fullPathDependencies = ;

        
         (string virtualDependency  virtualPathDependencies)
        {
           (fullPathDependencies == )
            fullPathDependencies =  System.Collections.Specialized.StringCollection();

          fullPathDependencies.Add(virtualDependency);
        }
         (fullPathDependencies == )
           ;

        
        string[] fullPathDependenciesArray =  string[fullPathDependencies.Count];
        fullPathDependencies.CopyTo(fullPathDependenciesArray, 0);
        
        string[] virtualPathArray =  string[1];
        virtualPathArray[0] = virtualPath;

          CacheDependency(virtualPathArray, fullPathDependenciesArray, utcStart);
      }
      
         Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
    }
  }



The second example is the XML data file used to populate the DataSet object returned by the custom VirtualPathProvider object.This XML data is used to demonstrate using the VirtualPathProvider, VirtualDirectory, and VirtualFile objects to retrieve data from external data and is not intended to represent a production-quality data store.

<?xml version="1.0" encoding="utf-8" ?>
  <resource type="dir" 
    path="/vrDir" 
    parentPath="" 
    content="">
    <resource type="file" 
      path="/vrDir/Level1FileA.vrf"
      parentPath="/vrDir" 
      content="This is the content of file Level1FileA.">
    </resource>
    <resource type="file" 
      path="/vrDir/Level1FileB.vrf"
      parentPath="/vrDir" 
      content="This is the content of file Level1FileB.">
    </resource>
    <resource type="dir" 
      path="/vrDir/Level2DirA" 
      parentPath="/vrDir" 
      content="">
    <resource type="file" 
      path="/vrDir/Level2DirA/Level2FileA.vrf" 
      parentPath="/vrDir/Level2DirA" 
      content="This is the content of file Level2FileA.">
    </resource>
    <resource type="file" 
      path="/vrDir/Level2DirA/Level2FileB.vrf"
      parentPath="/vrDir/Level2DirA" 
      content="This is the content of file Level2FileB.">
    </resource>
  </resource>
  <resource type="dir" 
    path="/vrDir/Level2DirB" 
    parentPath="/vrDir" 
    content="">
    <resource type="file" 
      path="/vrDir/Level2DirB/Level2FileA.vrf" 
      parentPath="/vrDir/Level2DirB" 
      content="This is the content of file Level2FileA.">
    </resource>
    <resource type="file" 
      path="/vrDir/Level2DirB/Level2FileB.vrf"
      parentPath="/vrDir/Level2DirB" 
      content="This is the content of file Level2FileB.">
    </resource>
  </resource>
</resource>

The third example provides an AppStart object that contains an AppInitialize method.Este método é chamado durante a inicialização de um aplicativo ASP.NET para executar qualquer Personalizar inicialização exigido.In this case, it registers the custom VirtualPathProvider object with the ASP.NET build system.

 System.Web.Hosting;

 Samples.AspNet.CS
{
  
  
  
  
     AppStart
  {
       AppInitialize()
    {
      SamplePathProvider sampleProvider =  SamplePathProvider();
      HostingEnvironment.RegisterVirtualPathProvider(sampleProvider);
    } 
  }
}


O último exemplo é uma página ASP.NET que contém vínculos para os arquivos virtuais contidos no sistema de arquivos virtual.


<%@ Page Language= %>

<!DOCTYPE html PUBLIC "-

<script runat=>

</script>

<html xmlns="http:
<head runat=>
  <meta http-equiv= content= />
  <title>Virtual Path Provider Example</title>
</head>
<body>
  <form id= runat=>
    <asp:HyperLink ID= runat= NavigateUrl= Text= /><br />
    <asp:HyperLink ID= runat= NavigateUrl= Text= /><br />
    <asp:HyperLink ID= runat= NavigateUrl= Text= /><br />
    <asp:HyperLink ID= runat= NavigateUrl= Text= /><br />
    <asp:HyperLink ID= runat= NavigateUrl= Text= /><br />
    <asp:HyperLink ID= runat= NavigateUrl= Text= /><br />
  </form>
</body>
</html>


System.MarshalByRefObject
  System.Object
    System.Web.Hosting.VirtualPathProvider
Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.
Isso foi útil para você?
(1500 caracteres restantes)

Contribuições da comunidade

ADICIONAR
© 2013 Microsoft. Todos os direitos reservados.