Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Thursday, September 14, 2006

.net WebResource.axd

Winform applications have been using resources (embedded images etc) for some time.  .NET allows developers to embed binary files into assemblies, which can later be retrieved by code at runtime.  ASP.NET is no exception.  How many times have you written a web control, which requires images, and you've had to rely on the client web site, using your control, having the correct images in the right location?  A better solution is to embed the images in the web control assembly and have ASP.NET pull the image at runtime.  This is where WebResource.axd comes in.  WebResource.axd is a build in ASP.NET  web handler that manages the rendering of resourced images on a client web browsers.

The following steps inform developers how to add an image resource to a web control assembly, and then have ASP.NET render the image using WebResource.axd.

1. Add the image to your web control project.
2. In the solution explorer, click the file, and in the property window, change build action to "embedded resource."
3. Add the following to your AssemblyInfo.cs file in the web control project:
[assembly: WebResourceAttribute("MyNameSpaces.MyControl.Images.MyImage.gif", "image/gif")]
Note:  "MyNameSpaces.MyControl" comes from the default namespace indicated in the web control project properties. "Images" is a folder in the web control project that contains "MyImage.gif".
4. In your control rendering code, you'll need the following to produce a usable URL for the image:
Page.ClientScript.GetWebResourceUrl(typeof(MyNameSpaces.MyControl), "MyNameSpaces.MyControl.Images.MyImage.gif")

The above steps produce a URL in your rendered control that looks something like:

Post a Comment