WebPartManager.IsAuthorized 方法

定义

确定能否将 WebPart 或其他服务器控件添加到页中。Determines whether a WebPart or other server control can be added to a page.

重载

IsAuthorized(WebPart)

执行确定控件是否被授权添加到页中的初始步骤。Carries out the initial steps in determining whether a control is authorized to be added to a page.

IsAuthorized(Type, String, String, Boolean)

执行确定控件是否已经过授权可添加至页的最后步骤。Carries out the final steps in determining whether a control is authorized to be added to a page.

注解

Web 部件功能的一个灵活性,就是在运行时将服务器控件添加到网页中。Part of the flexibility of the Web Parts feature is the ability to add server controls to Web pages at run time. 在许多常见情况下,服务器控件 (可以是自定义 WebPart 控件、自定义服务器控件、用户控件或 ASP.NET 控件) 可添加。There are a number of common scenarios in which a server control (which can be a custom WebPart control, a custom server control, a user control, or an ASP.NET control) can be added.

在下面的常见方案中,Web 部件控件集尝试将服务器控件添加到页,并 IsAuthorized 调用方法来授权它们:In the following common scenarios, the Web Parts control set attempts to add server controls to a page, and the IsAuthorized method is called to authorize them:

  • 添加服务器控件时,通过在区域内的网页的标记中对其进行声明来添加服务器控件 WebPartZoneBaseWhen a server control is added by declaring it in the markup of a Web page within a WebPartZoneBase zone.

  • 以编程方式将服务器控件添加到区域。When a server control is added programmatically to a zone.

  • 用户将服务器控件导入到 Web 部件的控件目录中。When a user imports a server control into a Web Parts catalog of controls.

  • 从个性化设置数据存储区加载现有服务器控件时。When an existing server control is loaded from the personalization data store.

  • 将服务器控件添加到 DeclarativeCatalogPart 控件,使其在服务器控件的目录中可用。When a server control is added to a DeclarativeCatalogPart control to make it available in a catalog of server controls.

在添加控件的每个方案中,将 IsAuthorized 调用方法以确保已满足所有授权条件,以允许添加控件。In each scenario where controls are added, the IsAuthorized method is called to ensure that all authorization criteria have been met to allow a control to be added. 当控件获得授权时,它将以正常方式添加(如果没有筛选方案)。When a control is authorized, it is added normally as it would be if there was no filtering scenario. 当控件未获得授权时,Web 部件控件集可以通过多种方式进行响应,具体取决于上下文。When a control is not authorized, the Web Parts control set can respond in several ways, depending on the context. 如果无需通知用户) ,控件集可以在无提示的情况下添加未经授权的部分 (,它可以显示错误消息,也可以将类的实例添加 UnauthorizedWebPart 为占位符。The control set can silently fail to add an unauthorized part (if there is no need to inform the user), it can display an error message, or it can add an instance of the UnauthorizedWebPart class as a placeholder. 此占位符对象在页面上不可见,但在页源代码中可见,表示排除了未经授权的控件。This placeholder object is not visible on the page, but is visible in the page source code to indicate that an unauthorized control was excluded.

控制是否获得授权的决定是授权筛选器。The determinant of whether a control is authorized is the authorization filter. 授权筛选器是 Web 部件控件集中的一项功能,它使开发人员可以从页中排除不满足指定条件的任何控件。An authorization filter is a feature in the Web Parts control set that enables developers to exclude from a page any controls that do not meet the specified criteria.

若要创建筛选方案,开发人员必须执行两项操作。To create a filtering scenario, developers must do two things. 首先,它们必须分配一个字符串值 (值可以任意) 到 AuthorizationFilter WebPart 计划在方案中使用的每个控件的属性。First, they must assign a string value (the value can be arbitrary) to the AuthorizationFilter property of each WebPart control they plan to use in the scenario. 它们还可以为不是控件的其他类型的服务器控件分配此属性的值 WebPart ,因为如果将这些控件放置在 WebPartZoneBase 区域中,则在运行时将此类控件与控件一起包装 GenericWebPart ,并且此控件继承 AuthorizationFilter 属性。They can also assign a value to this property for other types of server controls that are not WebPart controls, because if they are placed in WebPartZoneBase zones, such controls are wrapped with a GenericWebPart control at run time, and this control inherits the AuthorizationFilter property.

创建筛选方案的第二个必要步骤是重写 IsAuthorized(Type, String, String, Boolean) 方法,或创建事件的事件处理程序 AuthorizeWebPartThe second necessary step for creating a filtering scenario is to either override the IsAuthorized(Type, String, String, Boolean) method, or to create an event handler for the AuthorizeWebPart event. 在这些方法中,开发人员可以检查 AuthorizationFilter 属性,如果该值指示控件不应获得授权,开发人员可确保该 IsAuthorized 方法返回值 falseIn these methods, a developer can check the AuthorizationFilter property, and if the value indicates that the control should not be authorized, the developer ensures that the IsAuthorized method returns a value of false.

备注

有关代码示例和如何使用方法设置自定义筛选方案的说明 IsAuthorized ,请参阅方法重载主题。For code examples and a description of how to set up a customized filtering scenario using the IsAuthorized method, see the topics for the overloads of the method.

IsAuthorized(WebPart)

执行确定控件是否被授权添加到页中的初始步骤。Carries out the initial steps in determining whether a control is authorized to be added to a page.

public:
 bool IsAuthorized(System::Web::UI::WebControls::WebParts::WebPart ^ webPart);
public bool IsAuthorized (System.Web.UI.WebControls.WebParts.WebPart webPart);
member this.IsAuthorized : System.Web.UI.WebControls.WebParts.WebPart -> bool
Public Function IsAuthorized (webPart As WebPart) As Boolean

参数

webPart
WebPart

正在接受授权检查的 WebPart 或其他服务器控件。A WebPart or other server control being checked for authorization.

返回

Boolean

一个布尔值,指示能否将 webPart 添加到页中。A Boolean value that indicates whether webPart can be added to a page.

例外

webPartnullwebPart is null.

示例

下面的代码示例演示如何 IsAuthorized(WebPart) 从代码中调用方法,以确定是否有权将控件添加到页中。The following code example demonstrates how to call the IsAuthorized(WebPart) method from your code to determine whether a control is authorized to be added to a page.

此代码示例包含三个部分:The code example has three parts:

此代码示例使用一个自定义 WebPartManager 控件,该控件重写 IsAuthorized(Type, String, String, Boolean) 重载方法以提供对属性的自定义处理 AuthorizationFilterThis code example uses a custom WebPartManager control that overrides the IsAuthorized(Type, String, String, Boolean) overload method to provide custom handling of the AuthorizationFilter property. 此控件检查的属性值是否为, admin 如果值存在,则授权控件。This control checks for a property value of admin and, if the value is present, authorizes the control. 如果控件具有不同的值,则不会获得授权;不具有属性值的控件也会获得授权,因为它们不是筛选方案的一部分。If a control has a different value, it is not authorized; controls without the property value are authorized as well, as they are presumed not to be part of the filtering scenario.

若要运行此代码示例,必须编译此源代码。For this code example to run, you must compile this source code. 可以显式编译该程序集,并将生成的程序集放在网站的 Bin 文件夹或全局程序集缓存中。You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. 或者,您可以将源代码放在站点的 App_Code 文件夹中,它将在运行时动态编译。Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. 此代码示例使用动态编译方法。This code example uses the dynamic compile method. 有关演示如何编译的演练,请参阅 演练:开发和使用自定义 Web 服务器控件For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.

using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Samples.AspNet.CS.Controls
{
  public class MyManagerAuthorize : WebPartManager
  {
    public override bool IsAuthorized(Type type, string path, string authorizationFilter, bool isShared)
    {
      if (!String.IsNullOrEmpty(authorizationFilter))
      {
        if (authorizationFilter == "admin")
          return true;
        else
          return false;
      }
      else
            {
                return true;
            }
        }
  }
}
Imports System.Web
Imports System.Web.Security
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class MyManagerAuthorize
    Inherits WebPartManager

    Public Overrides Function IsAuthorized(ByVal type As Type, _
      ByVal path As String, ByVal authorizationFilter As String, _
      ByVal isShared As Boolean) As Boolean

      If Not String.IsNullOrEmpty(authorizationFilter) Then
        If authorizationFilter = "admin" Then
          Return True
        Else
          Return False
        End If
      Else
        Return True
      End If

    End Function

  End Class

End Namespace

此代码示例的第二部分创建可能排除控件的筛选器。The second part of the code example creates a filter that can potentially exclude a control. 以下网页包含元素中的三个 ASP.NET 服务器控件 <asp:webpartzone>The following Web page contains three ASP.NET server controls in an <asp:webpartzone> element. 请注意,第一个和第二个控件的 AuthorizationFilter 属性设置为不同的值,而第三个控件未分配属性。Notice that the first and second controls have their AuthorizationFilter properties set to different values, and the third does not assign the property. 此授权值可在运行时检查,如果筛选器与开发人员设置的条件匹配,则可以将控件添加到页面。This authorization value can be checked at run time, and the control can be added to the page if the filter matches criteria set by the developer. 另请注意,在 Page_Load 方法中,代码调用 IsAuthorized(WebPart) 方法来确定每个控件是否获得授权,如果是,则设置每个控件的 ExportMode 属性。Notice also that in the Page_Load method, the code calls the IsAuthorized(WebPart) method to determine whether each of the controls is authorized, and if so, it sets each control's ExportMode property.

<%@ Page Language="C#" %>
<%@ Register Namespace="Samples.AspNet.CS.Controls" 
    TagPrefix="aspSample"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  
  protected void Page_Load(object sender, EventArgs e)
  {
    foreach (WebPart part in mgr1.WebParts)
    {
      if (mgr1.IsAuthorized(part))
        part.ExportMode = WebPartExportMode.All;
    }
    
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <aspSample:MyManagerAuthorize ID="mgr1" runat="server"  />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <asp:BulletedList 
            ID="BulletedList1" 
            Runat="server"
            DisplayMode="HyperLink" 
            Title="Favorite Links"
            AuthorizationFilter="admin">
            <asp:ListItem Value="http://msdn.microsoft.com">
              MSDN
            </asp:ListItem>
            <asp:ListItem Value="http://www.asp.net">
              ASP.NET
            </asp:ListItem>
            <asp:ListItem Value="http://www.msn.com">
              MSN
            </asp:ListItem>
          </asp:BulletedList>
          <asp:Label ID="Label1" runat="server" 
            Text="Hello World"
            AuthorizationFilter="user" />
          <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
        </ZoneTemplate>
      </asp:WebPartZone>
      <hr />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>
<%@ Page Language="vb" %>
<%@ Register Namespace="Samples.AspNet.VB.Controls" 
    TagPrefix="aspSample"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    Dim part As WebPart
    For Each part In mgr1.WebParts
      If mgr1.IsAuthorized(part) Then
        part.ExportMode = WebPartExportMode.All
      End If
    Next
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <aspSample:MyManagerAuthorize ID="mgr1" runat="server"  />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <asp:BulletedList 
            ID="BulletedList1" 
            Runat="server"
            DisplayMode="HyperLink" 
            Title="Favorite Links"
            AuthorizationFilter="admin">
            <asp:ListItem Value="http://msdn.microsoft.com">
              MSDN
            </asp:ListItem>
            <asp:ListItem Value="http://www.asp.net">
              ASP.NET
            </asp:ListItem>
            <asp:ListItem Value="http://www.msn.com">
              MSN
            </asp:ListItem>
          </asp:BulletedList>
          <asp:Label ID="Label1" runat="server" 
            Text="Hello World"
            AuthorizationFilter="user" />
          <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
        </ZoneTemplate>
      </asp:WebPartZone>
      <hr />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

请注意,若要使代码示例正常运行,必须在 Web.config 文件中添加一个设置,以便导出 Web 部件说明文件。Note that for the code example to work, you must add a setting in the Web.config file to enable exporting Web Parts description files. 请确保在此代码示例的网页所在的同一目录中有一个 Web.config 文件。Ensure that you have a Web.config file in the same directory as the Web page for this code example. <system.web> 部分中,请确保有一个 <webParts> 元素的 enableExport 属性设置为 true ,如以下标记所示。Within the <system.web> section, make sure there is a <webParts> element with an enableExport attribute set to true, as in the following markup.

<webParts enableExport="true">

...

</webParts>

在浏览器中加载页面后,请注意,将显示第一个控件,因为它与重写的方法中的条件相匹配。After you load the page in a browser, note that the first control is displayed, because it matches the criteria in the overridden method. 不会将第二个控件添加到页面中,因为它已被筛选器排除。The second control is not added to the page, because it is excluded by the filter. 还添加了第三个控件,因为它没有设置其 AuthorizationFilter 属性。The third control is also added, because it does not have its AuthorizationFilter property set. 请注意,如果单击任一控件的标题栏中的谓词菜单图标,则可以导出它们,因为它们各自的 ExportMode 属性值已分配。Notice that if you click the verbs menu icon in the title bar of either control, they can both be exported because their respective ExportMode property values were assigned.

注解

IsAuthorized方法是 Web 部件控件集调用的初始方法,以检查控件的授权 WebPartThe IsAuthorized method is the initial method called by the Web Parts control set to check authorization for a WebPart control. 它接受 webPart 作为参数,并开始最终确定是否将控件添加到页面的进程。It accepts webPart as a parameter, and begins a process that ultimately determines whether the control will be added to a page. 需要确定给定控件是否已获得授权时,直接从代码调用此方法。Call this method from your code directly when you need to determine whether a given control is authorized.

此方法执行初始任务,这些任务确定控件是从类继承还是从控件继承, WebPart 如果是,则执行 GenericWebPart 其包含的子控件的类型。This method carries out the initial tasks of determining whether the control inherits from the WebPart class or is a GenericWebPart control and, if so, what type of child control it contains. 若要完成授权任务,它将调用 IsAuthorized(Type, String, String, Boolean) 重载方法。To finish the task of authorization, it calls the IsAuthorized(Type, String, String, Boolean) overload method.

调用方说明

此方法是从代码中直接调用的。This method is called directly from your code. 如果要对授权过程进行更多的编程控制,可以重写 IsAuthorized(Type, String, String, Boolean) 重载方法。If you want to gain greater programmatic control over the authorization process, you can override the IsAuthorized(Type, String, String, Boolean) overload method.

另请参阅

适用于

IsAuthorized(Type, String, String, Boolean)

执行确定控件是否已经过授权可添加至页的最后步骤。Carries out the final steps in determining whether a control is authorized to be added to a page.

public:
 virtual bool IsAuthorized(Type ^ type, System::String ^ path, System::String ^ authorizationFilter, bool isShared);
public virtual bool IsAuthorized (Type type, string path, string authorizationFilter, bool isShared);
abstract member IsAuthorized : Type * string * string * bool -> bool
override this.IsAuthorized : Type * string * string * bool -> bool
Public Overridable Function IsAuthorized (type As Type, path As String, authorizationFilter As String, isShared As Boolean) As Boolean

参数

type
Type

被检查授权情况的控件的 TypeThe Type of the control being checked for authorization.

path
String

被授权的控件的源文件的相对应用程序路径(如果该控件为用户控件)。The relative application path to the source file for the control being authorized, if the control is a user control.

authorizationFilter
String

赋予 AuthorizationFilter 控件的 WebPart 属性的任意字符串值,用于授权是否可将控件添加至页中。An arbitrary string value assigned to the AuthorizationFilter property of a WebPart control, used to authorize whether a control can be added to a page.

isShared
Boolean

指示被检查授权情况的控件是否为共享控件,共享意味着它对应用程序的许多用户或所有用户可见,并且其 IsShared 属性值设为 trueIndicates whether the control being checked for authorization is a shared control, meaning that it is visible to many or all users of the application, and its IsShared property value is set to true.

返回

Boolean

一个布尔值,指示控件是否已经过授权可添加至页中。A Boolean value that indicates whether a control is authorized to be added to a page.

例外

typenulltype is null.

type 为用户控件,且 pathnull 或空字符串 ("")。type is a user control, and path is either null or an empty string ("").

- 或 --or- type 不是用户控件,且 path 已赋值。type is not a user control, and path has a value assigned to it.

示例

下面的代码示例演示如何重写 IsAuthorized 方法,以确定是否有权将控件添加到页中。The following code example demonstrates how to override the IsAuthorized method to determine whether a control is authorized to be added to a page.

第一步是创建可能排除控件的筛选器。The first step is to create a filter that can potentially exclude a control. 以下网页包含元素中的三个 ASP.NET 服务器控件 <asp:webpartzone>The following Web page contains three ASP.NET server controls in an <asp:webpartzone> element. 请注意,第一个和第二个控件的 AuthorizationFilter 属性设置为不同的值,而第三个控件未分配属性。Notice that the first and second controls have their AuthorizationFilter properties set to different values, and the third does not assign the property. 此授权值可在运行时检查,如果筛选器与开发人员设置的条件匹配,则可以将控件添加到页面。This authorization value can be checked at run time, and the control can be added to the page if the filter matches criteria set by the developer.

<%@ Page Language="C#" %>
<%@ Register Namespace="Samples.AspNet.CS.Controls" 
    TagPrefix="aspSample"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  
  protected void Page_Load(object sender, EventArgs e)
  {
    foreach (WebPart part in mgr1.WebParts)
    {
      if (mgr1.IsAuthorized(part))
        part.ExportMode = WebPartExportMode.All;
    }
    
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <aspSample:MyManagerAuthorize ID="mgr1" runat="server"  />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <asp:BulletedList 
            ID="BulletedList1" 
            Runat="server"
            DisplayMode="HyperLink" 
            Title="Favorite Links"
            AuthorizationFilter="admin">
            <asp:ListItem Value="http://msdn.microsoft.com">
              MSDN
            </asp:ListItem>
            <asp:ListItem Value="http://www.asp.net">
              ASP.NET
            </asp:ListItem>
            <asp:ListItem Value="http://www.msn.com">
              MSN
            </asp:ListItem>
          </asp:BulletedList>
          <asp:Label ID="Label1" runat="server" 
            Text="Hello World"
            AuthorizationFilter="user" />
          <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
        </ZoneTemplate>
      </asp:WebPartZone>
      <hr />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>
<%@ Page Language="vb" %>
<%@ Register Namespace="Samples.AspNet.VB.Controls" 
    TagPrefix="aspSample"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    Dim part As WebPart
    For Each part In mgr1.WebParts
      If mgr1.IsAuthorized(part) Then
        part.ExportMode = WebPartExportMode.All
      End If
    Next
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <aspSample:MyManagerAuthorize ID="mgr1" runat="server"  />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <asp:BulletedList 
            ID="BulletedList1" 
            Runat="server"
            DisplayMode="HyperLink" 
            Title="Favorite Links"
            AuthorizationFilter="admin">
            <asp:ListItem Value="http://msdn.microsoft.com">
              MSDN
            </asp:ListItem>
            <asp:ListItem Value="http://www.asp.net">
              ASP.NET
            </asp:ListItem>
            <asp:ListItem Value="http://www.msn.com">
              MSN
            </asp:ListItem>
          </asp:BulletedList>
          <asp:Label ID="Label1" runat="server" 
            Text="Hello World"
            AuthorizationFilter="user" />
          <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
        </ZoneTemplate>
      </asp:WebPartZone>
      <hr />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

第二步是重写 IsAuthorized(Type, String, String, Boolean) 方法,并为授权筛选器创建自定义处理。The second step is to override the IsAuthorized(Type, String, String, Boolean) method, and create custom handling for authorization filters. 请注意,代码首先检查属性是否具有值,以便自动添加未分配属性的任何控件 AuthorizationFilterNote that the code first checks whether the property has a value, so that any control that does not assign the AuthorizationFilter property will be added automatically. 如果控件具有筛选器,则 true 仅当筛选器值等于时,代码才会返回 adminIf a control has a filter, the code returns true only if the filter value is equal to admin. 这说明了一种简单的机制,可用于根据特定用户的角色向某些用户显示特定控件。This demonstrates a simple mechanism you can use for displaying certain controls to certain users, depending on their role. 尽管使用角色的完整示例超出了本主题的范围,但你可以使用与此代码示例中的重写方法相同的逻辑,但你可以检查当前用户是否在与授权筛选器值匹配的角色中,然后仅为该用户添加控件。While a full example using roles is beyond the scope of this topic, you could use the same logic as the overridden method in this code example, except that you could check whether the current user is in a role that matches the authorization filter value, and then add the control only for that user. 这使您能够创建一些用户将看到所有控件的页面,而其他用户将只看到选定的控件。This would enable you to create pages where some users would see all the controls, and other users would see only selected controls. 这就是使用角色检查筛选器的逻辑的方式:This is how the logic that checks the filter might look if you used roles:

If Roles.IsUserInRole(Page.User.Identity.Name, authorizationFilter) Then  
  return True  
Else  
  return False  
End If  
if(Roles.IsUserInRole(Page.User.Identity.Name, authorizationFilter))  
    return true;  
else  
    return false;  

要使代码示例运行,必须编译此源代码。For the code example to run, you must compile this source code. 可以显式编译该程序集,并将生成的程序集放在网站的 Bin 文件夹或全局程序集缓存中。You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. 或者,您可以将源代码放在站点的 App_Code 文件夹中,它将在运行时动态编译。Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. 此代码示例使用动态编译方法。This code example uses the dynamic compile method. 有关演示如何编译的演练,请参阅 演练:开发和使用自定义 Web 服务器控件For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.

using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Samples.AspNet.CS.Controls
{
  public class MyManagerAuthorize : WebPartManager
  {
    public override bool IsAuthorized(Type type, string path, string authorizationFilter, bool isShared)
    {
      if (!String.IsNullOrEmpty(authorizationFilter))
      {
        if (authorizationFilter == "admin")
          return true;
        else
          return false;
      }
      else
            {
                return true;
            }
        }
  }
}
Imports System.Web
Imports System.Web.Security
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class MyManagerAuthorize
    Inherits WebPartManager

    Public Overrides Function IsAuthorized(ByVal type As Type, _
      ByVal path As String, ByVal authorizationFilter As String, _
      ByVal isShared As Boolean) As Boolean

      If Not String.IsNullOrEmpty(authorizationFilter) Then
        If authorizationFilter = "admin" Then
          Return True
        Else
          Return False
        End If
      Else
        Return True
      End If

    End Function

  End Class

End Namespace

在浏览器中加载页面后,请注意,将显示第一个控件,因为它与重写的方法中的条件相匹配。After you load the page in a browser, note that the first control is displayed, because it matches the criteria in the overridden method. 不会将第二个控件添加到页面,因为它的筛选器值已排除。The second control is not added to the page, because its filter value is excluded. 添加第三个控件,因为它没有 AuthorizationFilter 设置其属性。The third control is added, because it does not have its AuthorizationFilter property set. 如果在第二个控件上将属性值更改为与第一个控件的属性值相匹配,然后再次运行该页,则还将添加第二个控件。If you change the property value on the second control to match that of the first control, and then run the page again, the second control is added as well.

注解

IsAuthorized(Type, String, String, Boolean)重载方法执行确定是否有权将控件添加到页中的最后一个步骤。The IsAuthorized(Type, String, String, Boolean) overload method carries out the final steps in determining whether a control is authorized to be added to a page. 方法可确保 type 为有效类型,且 path 只有当要检查的控件是用户控件时才具有值。The method ensures that type is a valid type, and that path has a value only if the control being checked is a user control. 然后,它调用 OnAuthorizeWebPart 引发事件的关键方法 AuthorizeWebPartThen it calls the critical OnAuthorizeWebPart method, which raises the AuthorizeWebPart event.

继承者说明

WebPartManager如果要在检查授权时提供附加处理,可以通过从类继承来重写此方法。This method can be overridden by inheriting from the WebPartManager class, if you want to provide additional handling when checking authorization. 你可能想要重写方法以检查参数中的某些值 authorizationFilter ,并根据值返回一个布尔值,该值确定是否将控件添加到页中。You might want to override the method to check for certain values in the authorizationFilter parameter, and based on the value, return a Boolean value that determines whether the control will be added to a page.

对于还希望检查授权筛选器并提供自定义处理的页开发人员,可以选择在 .aspx 页或代码隐藏文件中执行此操作,而无需从任何类继承。For page developers who also want to check for authorization filters and provide custom handling, there is an option for doing this inline in an .aspx page, or in a code-behind file, without having to inherit from any classes. 可以在页中为控件的方法声明备用事件处理程序 OnAuthorizeWebPart(WebPartAuthorizationEventArgs) WebPartManagerYou can declare an alternate event handler in the page for the OnAuthorizeWebPart(WebPartAuthorizationEventArgs) method of the WebPartManager control. 有关更多详细信息和示例,请参见 OnAuthorizeWebPart(WebPartAuthorizationEventArgs) 方法。For more details and an example, see the OnAuthorizeWebPart(WebPartAuthorizationEventArgs) method.

另请参阅

适用于