Using the ASP.NET 2.0 Web Resource Attribute

ASP.NET 2.0 has a really nice feature that lets you compile site or component resources like javascript files into your assembly file instead of deploying these shared files to the wwwroot/aspnet_client directory like in ASP.NET 1.x. This makes your component/website much easier to deploy because it means you can keep everything you need in one file.

It’s pretty straight forward to do too (when you know how). You basically just need to add an embedded resource to your project, reference it in AssemblyInfo.cs using the WebResourceAttribute attribute and then use Page.ClientScript.GetWebResourceUrl() wherever you need to reference the file.

It took me ages to figure out how to get all the references right, so here are some more detailed step by step instructions on how to use it in your project.

1. Add resource to the project. You can put it in a subdirectory of the main project if you like, but this affects how the resource will be named.

2. Set the resource’s Build Action property to Embedded resource.

3. Add a WebResourceAttribute attribute to your AssemblyInfo.cs file (usually found in the Properties directory of your project).

You need to give the fully qualified name of the resource, which will include the default namespace of your project followed by the relative path to the file with directory slashes replaced by full stops. You will also need to provide a content type that will be sent to the browser:

[assembly: WebResourceAttribute("Examples.WebResource.Images.Elephant.jpg", "image/jpg")]

If you’re unsure about what the fully qualified name of your resource is, you can add some code to one of the class files in the project that will write the name of each embedded resource in the assembly to the debug output stream when the code is run:

string[] resources =
     this.GetType().Assembly.GetManifestResourceNames();
foreach (string resourceName in resources)
{
	Debug.WriteLine(resourceName);
}

4. Use the Page.ClientScript.GetWebResourceURL() method to reference your resource wherever you want to refer to it in your project. You will need to provide the same fully qualified name that you used to declare it in AssemblyInfo.cs:

this.ImgSrc =
    Page.ClientScript.GetWebResourceUrl(this.GetType(),
         "Examples.WebResource.Images.Elephant.jpg");

References:
Handling Client Files in ASP.NET 2.0
Nikhil Kothari’s overview of WebResourceAttribute
WebResourceAttribute API reference

Posted on 11 Jan 06 by Helen Emerson (last updated on 11 Jan 06).
Filed under ASP.NET, Server controls