ASP.NET 2.0提供的Web Resources管理模型,很好的解决了image、css、script等外部资源的管理问题。现在只需要在solution explorer把资源文件的build action属性设为Embedded Resource。然后在assemblyinfo.cs里添加一句:
[assembly: WebResource(
"
WebCtrl.cutecat.jpg
"
,
"
image/jpg
"
)]
其实这个语句放任何cs文件里,保证放在 最高级namespace外就行。
然后在程序中调用如下:
m_Image.ImageUrl
=
this
.Page.GetWebResourceUrl(
typeof
(WebCustom),
"
WebCtrl.cutecat.jpg
"
);
上面的语句返回给browser的代码是:
<
img
src
="WebResource.axd?a=pWebCtrl&r=WebCtrl.cutecat.jpg&t=632390947985312500"
style
="border-width:0px;"
/>
当然这个WebResource.axd是不存在的,它只是IIS中的一个ISAPI影射。
使用示例代码如下:
#region WebResource Demo
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("WebCtrl.cutecat.jpg", "image/jpg")]
namespace WebCtrl
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:WebCustom runat=server></{0}:WebCustom>")]
public class WebCustom : WebControl
{
private string text;
private Image m_Image;
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
public string Text
{
get { return text; }
set { text = value; }
}
protected override void CreateChildControls()
{
m_Image = new Image();
this.Controls.Add(m_Image);
}
protected override void Render(HtmlTextWriter output)
{
m_Image.ImageUrl = this.Page.GetWebResourceUrl(typeof(WebCustom), "WebCtrl.cutecat.jpg");
this.RenderChildren(output);
}
}
}