HOW TO:在 Visual Studio 中使用自訂 ASP.NET 伺服器控制項
更新:2007 年 11 月
您可以藉由定義適當的設計階段屬性 (Attribute) 給視覺化設計工具 (Visual Designer) 使用,讓自訂伺服器控制項能夠在 Visual Studio 工具箱中使用。下列程序會建立名為 MailLink 的簡單控制項,再將它包含在工具箱中,並透過呈現內容為 mailto: 統一資源定位器 (URL) 的超連結 <a> 項目,在 Web 網頁中使用這個控制項來建立電子郵件連結。
若要建立含有設計階段屬性的自訂控制項
在 Visual Studio 中,建立程式庫專案並定義衍生自 WebControl 的自訂類別,如下列範例所示。
注意事項: 完整的原始程式碼列於「範例」一節。
<Assembly: TagPrefix("Samples.AspNet", "Sample")> Namespace Samples.AspNet < _ ToolboxData("<{0}:MailLink ID='MailLinkID' Text='WebMaster' runat=""server""> </{0}:MailLink>")> _ Public Class MailLink Inherits WebControl ' Custom code goes here. End Class End Namespace
[assembly:TagPrefix("Samples.AspNet", "Sample")] namespace Samples.AspNet { [ ToolboxData("<{0}:MailLink ID='MailLinkID' Text='WebMaster' runat=\"server\"> </{0}:MailLink>") ] public class MailLink : WebControl { // Custom code goes here. } }
加入設計階段屬性,以便在設計階段提供要用來在視覺化設計工具中顯示控制項的自訂中繼資料 (Metadata)。如果要讓 MailLink 控制項能夠在 Visual Studio 工具箱中使用,唯一需要的是以下兩個設計階段屬性。
TagPrefix 屬性會在控制項名稱 MailLink 前面指定前置詞。前置詞加控制項名稱便定義出自訂控制項的標記 (Tag) 名稱 (在本例中為 <Sample:MailLink> </Sample:MailLink>)。
<Assembly: TagPrefix("Samples.AspNet", "Sample")>
[assembly:TagPrefix("Samples.AspNet", "Sample")]
在設計階段,將 MailLink 控制項從工具箱拖曳到網頁時,ToolboxData 屬性則會為該控制項指定預設的標記。
<ToolboxData("<{0}:MailLink ID='MailLinkID' Text='Mail Webmaster' runat='server'"> </{0}:MailLink>")>
[ToolboxData("<{0}:MailLink ID='MailLinkID' Text='Mail Webmaster' runat=\"server\"> </{0}:MailLink>")]
在程式庫中編譯 MailLink 控制項,並命名為 MaiLink.Dll。
若要將自訂控制項加入至工具箱
在 [檢視] 功能表上,按一下 [工具箱]。
在 [工具箱] 中,以滑鼠右鍵按一下並選取 [選擇項目]。
在 [選擇工具箱項目] 對話方塊中,選取 [.NET Framework 元件] 索引標籤,然後按一下 [瀏覽] 按鈕,以便找出剛才建置 (Build) 的 MailLink.Dll。
選取 MailLink 控制項的核取方塊,然後按一下 [確定]。
[工具箱] 中便會出現 MailLink 控制項。
若要在網頁中參考 MailLink 控制項
建立新的 Web 專案,然後建立名為 MailLink.aspx 的網頁。根據選取的專案語言不同,這個網頁將包含下列其中一個指示詞。
<%@ page language="VB" %>
<%@ page language="C#" %>
加入下列基本網頁結構,以便裝載 (Host) MailLink 控制項。
<html xmlns="http://www.w3.org/1999/xhtml" > <head > <title>Using the MailLink control</title> </head> <body> <h1>Using the MailLink Custom Server Control</h1> <form id="form1" > <div> </div> </form> </body> </html>
切換至設計檢視,並將 MailLink 控制項拖曳到網頁上。
Visual Studio 會將以下兩個項目加入至網頁:MailLink 控制項的 Register 指示詞,以及要在網頁中使用之 MailLink 控制項的標記名稱。
在瀏覽器中執行該網頁,然後按一下 [Mail Webmaster] 連結。
電子郵件便會開啟,而其收件者地址是由該控制項的 Email 屬性所指定。
範例
MailLink 控制項會覆寫 TagKey 屬性,以呈現 <a> 項目而非 WebControl 類別所呈現的預設 <span> 項目。
Imports System
Imports System.ComponentModel
Imports System.Security
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
<Assembly: TagPrefix("Samples.AspNet", "Sample")>
Namespace Samples.AspNet
<AspNetHostingPermission( _
SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission( _
SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
ParseChildren(True, "Text"), _
DefaultProperty("Email"), _
ToolboxData("<{0}:MailLink ID='MailLinkID' Text='Mail Web Master' runat=""server""> </{0}:MailLink>")> _
Public Class MailLink
Inherits WebControl
<Browsable(True), Category("Appearance"), _
DefaultValue("webmaster@contoso.com"), _
Description("The e-mail address.")> _
Public Overridable Property Email() As String
Get
Dim s As String = CStr(ViewState("Email"))
If s Is Nothing Then s = "webmaster@contoso.com"
Return s
End Get
Set(ByVal value As String)
ViewState("Email") = value
End Set
End Property
<Browsable(True), Category("Appearance"), _
DefaultValue("Web Master"), _
Description("The name to display."), _
Localizable(True), _
PersistenceMode(PersistenceMode.InnerDefaultProperty)> _
Public Overridable Property [Text]() As String
Get
Dim s As String = CStr(ViewState("Text"))
If s Is Nothing Then s = String.Empty
Return s
End Get
Set(ByVal value As String)
ViewState("Text") = value
End Set
End Property
Protected Overrides ReadOnly Property TagKey() _
As HtmlTextWriterTag
Get
Return HtmlTextWriterTag.A
End Get
End Property
Protected Overrides Sub AddAttributesToRender(ByVal writer _
As HtmlTextWriter)
MyBase.AddAttributesToRender(writer)
writer.AddAttribute( _
HtmlTextWriterAttribute.Href, "mailto:" + Email)
End Sub 'AddAttributesToRender
Protected Overrides Sub RenderContents(ByVal writer _
As HtmlTextWriter)
If [Text] = String.Empty Then
[Text] = Email
End If
writer.WriteEncodedText([Text])
End Sub 'RenderContents
End Class 'MailLink
End Namespace
using System;
using System.ComponentModel;
using System.Security;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly:TagPrefix("Samples.AspNet", "Sample")]
namespace Samples.AspNet
{
[
AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
ParseChildren(true, "Text"),
DefaultProperty("Email"),
ToolboxData("<{0}:MailLink ID='MailLinkID' Text='Mail Web Master' runat=\"server\"> </{0}:MailLink>")
]
public class MailLink : WebControl
{
[
Browsable(true),
Category("Appearance"),
DefaultValue("webmaster@contoso.com"),
Description("The e-mail address.")
]
public virtual string Email
{
get
{
string s = (string)ViewState["Email"];
return (s == null) ? "webmaster@contoso.com" : s;
}
set
{
ViewState["Email"] = value;
}
}
[
Browsable(true),
Category("Appearance"),
DefaultValue("Web Master"),
Description("The name to display."),
Localizable(true),
PersistenceMode(PersistenceMode.InnerDefaultProperty)
]
public virtual string Text
{
get
{
string s = (string)ViewState["Text"];
return (s == null) ? String.Empty : s;
}
set
{
ViewState["Text"] = value;
}
}
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.A;
}
}
protected override void AddAttributesToRender(
HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Href,
"mailto:" + Email);
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (Text == String.Empty)
{
Text = Email;
}
writer.WriteEncodedText(Text);
}
}
}
MailLink 控制項也會顯示內部文字持續性 (Persistence)。MailLink 可讓網頁開發人員指定控制項之標記內的 Text 屬性,如下列範例所示。
<Sample:MailLink id="MaillinkID" Email="Webmaster@contoso.com"
>
Mail Support Team
</Sample:MailLink>
內部持續性和控制項之開頭標記上的預設持續性形成對比,如下列範例所示。
<Sample:MailLink Text="Mail Webmaster" > </Sample:MailLink>
前面的程式碼是將控制項從工具箱拖曳到網頁時為該控制項產生的預設標記。
編譯程式碼
在 Visual Studio 中,建立程式庫專案並定義衍生自 WebControl 的自訂類別,如上述程序所示。完整的原始程式碼列於前面的程式碼一節。
安全性
自訂伺服器控制項會擴充 ASP.NET 的功能,因此必須遵循一些確切的安全性方針。尤其要考慮以下幾點:
執行階段和設計階段安全性。
在強式名稱之組件中的自訂控制項。
在裝載自訂伺服器控制項之伺服器上的作業系統安全性和存取控制清單 (ACL)。
限制控制項可存取之資源的程式碼存取安全性。
在全域組件快取中的 Managed 組件。