ASP.NET(1.0/1.1)給我們提供了一個開發WebControl的編程模型,於是我們擺脫了asp裡面的include模式的複用方式。不過1.0/1.1提供的Web控制項開發模型對於處理沒有image、css等外部資源的組件還算比較得心應手,script雖然很多時候也是外部資源,但在開發控制項的時候我們習慣把script使用Page.Register...Script()來嵌入模組,因為緊湊的東西更便於我們複用,用一個dll就可以解決問題又何必要節外生枝呢。
ASP.NET 2.0提供的Web Resources管理模型,很好的解決了image、css、script等外部資源的管理問題。現在只需要在solution explorer把資源檔的build action屬性設為Embedded Resource。然後在assemblyinfo.cs裡添加一句: [assembly: WebResource("WebCtrl.cutecat.jpg", "image/jpg")]
我們可以看msdn裡有WebResource的參數說明:第一個是資源的名字,第二個是資源的mime-type名。
其實這個語句放任何cs檔案裡,保證放在最進階namespace外就行。
然後在程式中調用如下: m_Image.ImageUrl = this.Page.GetWebResourceUrl(typeof(WebCustom), "WebCtrl.cutecat.jpg");
GetWebResourceUrl的第一個參數是使用者定義的類型(這個是用來確定assembly用的),第二個參數是資源名。
上面的語句返回給browser的代碼是: <img src="WebResource.axd?a=pWebCtrl&r=WebCtrl.cutecat.jpg&t=632390947985312500" style="border-width:0px;" />
其中的src就是GetWebesourceUrl執行後返回的,它有3個參數(這裡的&被解析成了&,不過IIS也認的),第一個參數a是就是通過typeof(WebCustom)來確定的assembly的名字,第二個參數r很明顯就是資源的名字了,第三個參數t是一個a所指的assembly的timestamp。這個t是為了讓資源的引用能享用browser緩衝的最佳化,因為IE對相同的url有自己的cache機制。又因為這個r同時又是使用者assembly檔案的timestamp,如果使用者更新了代碼,重新編譯後t也會變化,這樣也就保證了browser能獲得最新的資源更新。如果我們能確定嵌入資源是確實不用再更新的,我們可以在typeof()裡寫一個bcl裡的類型,比如typeof(string),那麼他將只在freamwork升級後才會變動這個t。
當然這個WebResource.axd是不存在的,它只是IIS中的一個ISAPI影射。
使用範例程式碼如下: WebResource Demo#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);
}
}
}
#endregion