WebResourceAttribute Clase
Definición
Define el atributo de metadatos que habilita un recurso incrustado en un ensamblado.Defines the metadata attribute that enables an embedded resource in an assembly. Esta clase no puede heredarse.This class cannot be inherited.
public ref class WebResourceAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple=true)]
public sealed class WebResourceAttribute : Attribute
type WebResourceAttribute = class
inherit Attribute
Public NotInheritable Class WebResourceAttribute
Inherits Attribute
- Herencia
- Atributos
Ejemplos
Esta sección contiene dos ejemplos de código.This section contains two code examples. En el primer ejemplo de código se muestra cómo WebResourceAttribute aplicar el atributo a un espacio de nombres que define MyCustomControl
un control personalizado,.The first code example demonstrates how to apply the WebResourceAttribute attribute to a namespace that defines a custom control, MyCustomControl
. En el segundo ejemplo de código se muestra cómo MyCustomControl
usar la clase en una página web.The second code example demonstrates how to use the MyCustomControl
class in a Web page.
En el ejemplo de código siguiente se muestra cómo WebResourceAttribute aplicar el atributo en un ensamblado personalizado para definir un recurso Web de imagen y un recurso web HTML.The following code example demonstrates how to apply the WebResourceAttribute attribute on a custom assembly to define an image Web resource and an HTML Web resource. La MyCustomControl
clase define un control compuesto que utiliza los recursos para establecer el valor de la ImageUrl propiedad de un Image control que se encuentra dentro del control compuesto y para establecer la HRef propiedad de un HtmlAnchor Controle el vínculo al recurso HTML.The MyCustomControl
class defines a composite control that uses the resources to set the value of the ImageUrl property of an Image control that is contained within the composite control and to set the HRef property of an HtmlAnchor control linking to the HTML resource.
using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
[assembly: WebResource("image1.jpg", "image/jpeg")]
[assembly: WebResource("help.htm", "text/html", PerformSubstitution=true)]
namespace Samples.AspNet.CS.Controls
{
public class MyCustomControl : Control
{
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
protected override void CreateChildControls()
{
// Create a new Image control.
Image _img = new Image();
_img.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(MyCustomControl), "image1.jpg");
this.Controls.Add(_img);
// Create a new Label control.
Label _lab = new Label();
_lab.Text = "A composite control using the WebResourceAttribute class.";
this.Controls.Add(_lab);
// Create a new HtmlAnchor control linking to help.htm.
HtmlAnchor a = new HtmlAnchor();
a.HRef = this.Page.ClientScript.GetWebResourceUrl(typeof(MyCustomControl), "help.htm");
a.InnerText = "help link";
this.Controls.Add(new LiteralControl("<br />"));
this.Controls.Add(a);
}
}
}
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
<Assembly: WebResource("image1.gif", "image/jpeg")>
<Assembly: WebResource("help.htm", "text/html", PerformSubstitution:=True)>
Namespace Samples.AspNet.VB.Controls
Public Class MyCustomControl
Inherits Control
<System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
Protected Overrides Sub CreateChildControls()
' Create a new Image control.
Dim _img As New Image()
_img.ImageUrl = Me.Page.ClientScript.GetWebResourceUrl(GetType(MyCustomControl), "image1.jpg")
Me.Controls.Add(_img)
' Create a new Label control.
Dim _lab As New Label()
_lab.Text = "A composite control using the WebResourceAttribute class."
Me.Controls.Add(_lab)
' Create a new HtmlAnchor control linking to help.htm.
Dim a As HtmlAnchor = New HtmlAnchor()
a.HRef = Me.Page.ClientScript.GetWebResourceUrl(GetType(MyCustomControl), "help.htm")
a.InnerText = "help link"
Me.Controls.Add(New LiteralControl("<br />"))
Me.Controls.Add(a)
End Sub
End Class
End Namespace
En el ejemplo de código siguiente se muestra cómo MyCustomControl
usar la clase en una página web.The following code example demonstrates how to use the MyCustomControl
class in a Web page.
<%@ Page Language="C#" %>
<%@ Register TagPrefix="AspNetSamples" Namespace="Samples.AspNet.CS.Controls" Assembly="Samples.AspNet.CS.Controls" %>
<%@ Import Namespace="System.Reflection" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// Get the assembly metatdata.
Type clsType = typeof(MyCustomControl);
Assembly a = clsType.Assembly;
// Iterate through the attributes for the assembly.
foreach (Attribute attr in Attribute.GetCustomAttributes(a))
{
//Check for WebResource attributes.
if (attr.GetType() == typeof(WebResourceAttribute))
{
WebResourceAttribute wra = (WebResourceAttribute)attr;
Response.Write("Resource in the assembly: " + wra.WebResource.ToString() +
" with ContentType = " + wra.ContentType.ToString() +
" and PerformsSubstitution = " + wra.PerformSubstitution.ToString() + "</br>");
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>WebResourceAttribute Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<AspNetSamples:MyCustomControl id="MyCustomControl1" runat="server">
</AspNetSamples:MyCustomControl>
</div>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Register TagPrefix="AspNetSamples" Namespace="Samples.AspNet.VB.Controls" Assembly="Samples.AspNet.VB.Controls" %>
<%@ Import Namespace="System.Reflection" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Get the assembly metatdata.
Dim clsType As Type = GetType(MyCustomControl)
Dim a As Assembly = clsType.Assembly
For Each attr As Attribute In Attribute.GetCustomAttributes(a)
'Check for WebResource attributes.
If attr.GetType() Is GetType(WebResourceAttribute) Then
Dim wra As WebResourceAttribute = CType(attr, WebResourceAttribute)
Response.Write("Resource in the assembly: " & wra.WebResource.ToString() & _
" with ContentType = " & wra.ContentType.ToString() & _
" and PerformsSubstitution = " & wra.PerformSubstitution.ToString() & "</br>")
End If
Next attr
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>WebResourceAttribute Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<AspNetSamples:MyCustomControl id="MyCustomControl1" runat="server">
</AspNetSamples:MyCustomControl>
</div>
</form>
</body>
</html>
En este ejemplo, es necesario compilar los recursos image1. jpg y help. htm con el MyCustomControl
ensamblado que contiene.This example requires that you compile the Image1.jpg and Help.htm resources with the assembly that contains MyCustomControl
. Para obtener más información, vea, /ResourceC# (opciones del compilador) o /Resource (Visual Basic).For more information, see, /resource (C# Compiler Options) or /resource (Visual Basic).
A continuación se muestra un ejemplo de un recurso web HTML que podría usarse en este ejemplo.An example of an HTML Web resource that could be used in this example is shown next. Tenga en cuenta el uso WebResource
de la sintaxis, que se usa cuando se PerformSubstitution establece la true
propiedad en para un recurso Web.Note the use of the WebResource
syntax, which is used when you set the PerformSubstitution property to true
for a Web resource.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head>
<title>Included Help Page</title>
</head>
<body>
<div>
<img alt="help image" src=<% = WebResource("image1.jpg") %> />
Included help file.
</div>
</body>
</html>
Comentarios
La WebResourceAttribute clase solo es válida cuando se usa en declaraciones de ensamblado.The WebResourceAttribute class is valid only when used on assembly declarations. Se utiliza para habilitar un recurso incrustado especificado en un ensamblado para su uso como un recurso Web.It is used to enable a specified embedded resource in an assembly for use as a Web resource.
Para obtener más información sobre los recursos, consulte información general sobre los recursos de página web de ASP.net.For more information on resources, see ASP.NET Web Page Resources Overview.
Constructores
WebResourceAttribute(String, String) |
Inicializa una nueva instancia de la clase WebResourceAttribute con el recurso Web especificado y el tipo de contenido del recurso.Initializes a new instance of the WebResourceAttribute class with the specified Web resource and resource content type. |
Propiedades
CdnPath |
Obtiene o establece la ruta de acceso a una red de distribución de contenido (CDN) que contiene recursos web.Gets or set the path of a Content Delivery Network (CDN) that contains Web resources. |
CdnSupportsSecureConnection |
Obtiene o establece un valor que indica a ScriptManager si se debe tener acceso a un recurso de script usando una conexión segura a la ruta de acceso a la red de distribución de contenido (CDN) cuando se tiene acceso a la página mediante HTTPS.Gets or set a value that indicates to the ScriptManager whether a script resource should be accessed using a secure connection to the content delivery network (CDN) path when the page is accessed using HTTPS. |
ContentType |
Obtiene una cadena que contiene el tipo MIME del recurso al que hace referencia la clase WebResourceAttribute.Gets a string containing the MIME type of the resource that is referenced by the WebResourceAttribute class. |
LoadSuccessExpression |
Obtiene o establece una expresión que se utiliza cuando un recurso web se ha cargado correctamente.Gets or sets an expression that is used when a Web resource has successfully loaded. |
PerformSubstitution |
Obtiene o establece un valor booleano que determina si durante el procesamiento del recurso incrustado al que hizo referencia la clase WebResourceAttribute, se analizan y se reemplazan otras direcciones URL del recurso Web con la ruta de acceso completa al recurso.Gets or sets a Boolean value that determines whether, during processing of the embedded resource referenced by the WebResourceAttribute class, other Web resource URLs are parsed and replaced with the full path to the resource. |
TypeId |
Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Heredado de Attribute) |
WebResource |
Obtiene una cadena que contiene del recurso al que hace referencia la clase WebResourceAttribute.Gets a string containing the name of the resource that is referenced by the WebResourceAttribute class. |
Métodos
Equals(Object) |
Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. (Heredado de Attribute) |
GetHashCode() |
Devuelve el código hash de esta instancia.Returns the hash code for this instance. (Heredado de Attribute) |
GetType() |
Obtiene el Type de la instancia actual.Gets the Type of the current instance. (Heredado de Object) |
IsDefaultAttribute() |
Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Heredado de Attribute) |
Match(Object) |
Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Heredado de Attribute) |
MemberwiseClone() |
Crea una copia superficial del Object actual.Creates a shallow copy of the current Object. (Heredado de Object) |
ToString() |
Devuelve un valor de tipo string que representa el objeto actual.Returns a string that represents the current object. (Heredado de Object) |
Implementaciones de interfaz explícitas
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers. (Heredado de Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.Retrieves the type information for an object, which can be used to get the type information for an interface. (Heredado de Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Heredado de Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object. (Heredado de Attribute) |
Se aplica a
Consulte también:
- Attribute
- Información general de los recursos de página web de ASP.NETASP.NET Web Page Resources Overview
- Recursos en aplicacionesResources in Applications
- /Resource (incrustar archivo de recursos en laC# salida) (opciones del compilador)/resource (Embed Resource File to Output) (C# Compiler Options)
- /resource (Visual Basic)/resource (Visual Basic)
- Empaquetar e implementar recursosPackaging and Deploying Resources