RoleManagerSection Класс

Определение

Определяет параметры конфигурации, обеспечивающие поддержку инфраструктуры управления ролями в веб-приложениях. Этот класс не наследуется.

public ref class RoleManagerSection sealed : System::Configuration::ConfigurationSection
public sealed class RoleManagerSection : System.Configuration.ConfigurationSection
type RoleManagerSection = class
    inherit ConfigurationSection
Public NotInheritable Class RoleManagerSection
Inherits ConfigurationSection
Наследование

Примеры

В этом разделе приведены два примера кода. В первом примере показано, как декларативно указать значения для нескольких свойств RoleManagerSection класса. Во втором демонстрируется использование RoleManagerSection типа.

В следующем примере файла конфигурации показано, как декларативно указать значения для нескольких свойств RoleManagerSection класса.

<system.web>  
  <roleManager   
    enabled="false"   
    cacheRolesInCookie="false"   
    cookieName=".ASPXROLES" cookieTimeout="30"  
    cookiePath="/" cookieRequireSSL="false"  
    cookieSlidingExpiration="true" createPersistentCookie="false"  
    cookieProtection="All"   
    defaultProvider="AspNetSqlRoleProvider"  
    maxCachedResults="25"  >  
    <providers>  
      <add   
        name="AspNetSqlRoleProvider"  
        connectionStringName="LocalSqlServer"   
        applicationName="/"  
        type="System.Web.Security.SqlRoleProvider, System.Web,  
          Version=2.0.3600.0, Culture=neutral,  
          PublicKeyToken=b03f5f7f11d50a3a" />  
      <add   
        name="AspNetWindowsTokenRoleProvider"   
        applicationName="/"  
        type="System.Web.Security.WindowsTokenRoleProvider, System.Web,   
          Version=2.0.3600.0, Culture=neutral,   
          PublicKeyToken=b03f5f7f11d50a3a" />  
    </providers>  
  </roleManager>  
</system.web>  

В следующем примере кода показано, как использовать RoleManagerSection тип.

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web;
using System.Web.Configuration;

#endregion

namespace Samples.Aspnet.SystemWebConfiguration
{
  class UsingRoleManagerSection
  {
    static void Main(string[] args)
    {
      try
      {
        // Set the path of the config file.
        string configPath = "";

        // Get the Web application configuration object.
        Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

        // Get the section related object.
        RoleManagerSection configSection =
          (RoleManagerSection)config.GetSection("system.web/roleManager");

        // Display title and info.
        Console.WriteLine("ASP.NET Configuration Info");
        Console.WriteLine();

        // Display Config details.
        Console.WriteLine("File Path: {0}",
          config.FilePath);
        Console.WriteLine("Section Path: {0}",
          configSection.SectionInformation.Name);

        // Display CacheRolesInCookie property.
        Console.WriteLine("CacheRolesInCookie: {0}",
          configSection.CacheRolesInCookie);

        // Set CacheRolesInCookie property.
        configSection.CacheRolesInCookie = false;

        // Display CookieName property.
        Console.WriteLine("CookieName: {0}", configSection.CookieName);

        // Set CookieName property.
        configSection.CookieName = ".ASPXROLES";

        // Display CookiePath property.
        Console.WriteLine("CookiePath: {0}", configSection.CookiePath);

        // Set CookiePath property.
        configSection.CookiePath = "/";

        // Display CookieProtection property.
        Console.WriteLine("CookieProtection: {0}",
          configSection.CookieProtection);

        // Set CookieProtection property.
        configSection.CookieProtection =
          System.Web.Security.CookieProtection.All;

        // Display CookieRequireSSL property.
        Console.WriteLine("CookieRequireSSL: {0}",
          configSection.CookieRequireSSL);

        // Set CookieRequireSSL property.
        configSection.CookieRequireSSL = false;

        // Display CookieSlidingExpiration property.
        Console.WriteLine("CookieSlidingExpiration: {0}",
          configSection.CookieSlidingExpiration);

        // Set CookieSlidingExpiration property.
        configSection.CookieSlidingExpiration = true;

        // Display CookieTimeout property.
        Console.WriteLine("CookieTimeout: {0}", configSection.CookieTimeout);

        // Set CookieTimeout property.
        configSection.CookieTimeout = TimeSpan.FromMinutes(30);

        // Display CreatePersistentCookie property.
        Console.WriteLine("CreatePersistentCookie: {0}",
          configSection.CreatePersistentCookie);

        // Set CreatePersistentCookie property.
        configSection.CreatePersistentCookie = false;

        // Display DefaultProvider property.
        Console.WriteLine("DefaultProvider: {0}",
          configSection.DefaultProvider);

        // Set DefaultProvider property.
        configSection.DefaultProvider = "AspNetSqlRoleProvider";

        // Display Domain property.
        Console.WriteLine("Domain: {0}", configSection.Domain);

        // Set Domain property.
        configSection.Domain = "";

        // Display Enabled property.
        Console.WriteLine("Enabled: {0}", configSection.Enabled);

        // Set Enabled property.
        configSection.Enabled = false;

        // Display the number of Providers
        Console.WriteLine("Providers Collection Count: {0}",
          configSection.Providers.Count);

        // Display elements of the Providers collection property.
        foreach (ProviderSettings providerItem in configSection.Providers)
        {
          Console.WriteLine();
          Console.WriteLine("Provider Details:");
          Console.WriteLine("Name: {0}", providerItem.Name);
          Console.WriteLine("Type: {0}", providerItem.Type);
        }

        // Update if not locked.
        if (!configSection.SectionInformation.IsLocked)
        {
          config.Save();
          Console.WriteLine("** Configuration updated.");
        }
        else
        {
          Console.WriteLine("** Could not update, section is locked.");
        }
      }

      catch (Exception e)
      {
        // Unknown error.
        Console.WriteLine(e.ToString());
      }

      // Display and wait
      Console.ReadLine();
    }
  }
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Web
Imports System.Web.Configuration

Namespace Samples.Aspnet.SystemWebConfiguration
  Class UsingRoleManagerSection
    Public Shared Sub Main()
      Try
        ' Set the path of the config file.
        Dim configPath As String = ""

        ' Get the Web application configuration object.
        Dim config As System.Configuration.Configuration = _
         System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath)

        ' Get the section related object.
        Dim configSection As System.Web.Configuration.RoleManagerSection = _
         CType(config.GetSection("system.web/roleManager"), _
         System.Web.Configuration.RoleManagerSection)

        ' Display title and info.
        Console.WriteLine("ASP.NET Configuration Info")
        Console.WriteLine()

        ' Display Config details.
        Console.WriteLine("File Path: {0}", config.FilePath)
        Console.WriteLine("Section Path: {0}", configSection.SectionInformation.Name)

        ' Display CacheRolesInCookie property.
        Console.WriteLine("CacheRolesInCookie: {0}", _
         configSection.CacheRolesInCookie)

        ' Set CacheRolesInCookie property.
        configSection.CacheRolesInCookie = False

        ' Display CookieName property.
        Console.WriteLine("CookieName: {0}", configSection.CookieName)

        ' Set CookieName property.
        configSection.CookieName = ".ASPXROLES"

        ' Display CookiePath property.
        Console.WriteLine("CookiePath: {0}", configSection.CookiePath)

        ' Set CookiePath property.
        configSection.CookiePath = "/"

        ' Display CookieProtection property.
        Console.WriteLine("CookieProtection: {0}", _
         configSection.CookieProtection)

        ' Set CookieProtection property.
        configSection.CookieProtection = _
         System.Web.Security.CookieProtection.All

        ' Display CookieRequireSSL property.
        Console.WriteLine("CookieRequireSSL: {0}", _
         configSection.CookieRequireSSL)

        ' Set CookieRequireSSL property.
        configSection.CookieRequireSSL = False

        ' Display CookieSlidingExpiration property.
        Console.WriteLine("CookieSlidingExpiration: {0}", _
         configSection.CookieSlidingExpiration)

        ' Set CookieSlidingExpiration property.
        configSection.CookieSlidingExpiration = True

        ' Display CookieTimeout property.
        Console.WriteLine("CookieTimeout: {0}", configSection.CookieTimeout)

        ' Set CookieTimeout property.
        configSection.CookieTimeout = TimeSpan.FromMinutes(30)

        ' Display CreatePersistentCookie property.
        Console.WriteLine("CreatePersistentCookie: {0}", _
         configSection.CreatePersistentCookie)

        ' Set CreatePersistentCookie property.
        configSection.CreatePersistentCookie = False

        ' Display DefaultProvider property.
        Console.WriteLine("DefaultProvider: {0}", _
         configSection.DefaultProvider)

        ' Set DefaultProvider property.
        configSection.DefaultProvider = "AspNetSqlRoleProvider"

        ' Display Domain property.
        Console.WriteLine("Domain: {0}", configSection.Domain)

        ' Set Domain property.
        configSection.Domain = ""

        ' Display Enabled property.
        Console.WriteLine("Enabled: {0}", configSection.Enabled)

        ' Set CookieName property.
        configSection.Enabled = False

        ' Display the number of Providers
        Console.WriteLine("Providers Collection Count: {0}", _
         configSection.Providers.Count)

        ' Display elements of the Providers collection property.
        For Each providerItem As ProviderSettings In configSection.Providers()
          Console.WriteLine()
          Console.WriteLine("Provider Details:")
          Console.WriteLine("Name: {0}", providerItem.Name)
          Console.WriteLine("Type: {0}", providerItem.Type)
        Next

        ' Update if not locked.
        If Not configSection.SectionInformation.IsLocked Then
          config.Save()
          Console.WriteLine("** Configuration updated.")
        Else
          Console.WriteLine("** Could not update, section is locked.")
        End If

      Catch e As Exception
        ' Unknown error.
        Console.WriteLine(e.ToString())
      End Try

      ' Display and wait
      Console.ReadLine()
    End Sub
  End Class
End Namespace

Комментарии

Класс RoleManagerSection предоставляет способ программного доступа и изменения содержимого roleManager раздела файла конфигурации.

Конструкторы

RoleManagerSection()

Инициализирует новый экземпляр класса RoleManagerSection с использованием параметров по умолчанию.

Свойства

CacheRolesInCookie

Получает или задает значение, определяющее кэширование ролей текущего пользователя с использованием файла cookie.

CookieName

Получает или задает имя файла cookie, который используется для кэширования имен ролей.

CookiePath

Получает или задает виртуальный путь файла cookie, который используется для кэширования имен ролей.

CookieProtection

Получает или задает тип защиты файла cookie, который используется для кэширования имен ролей.

CookieRequireSSL

Получает или задает значение, определяющее необходимость применения подключения по протоколу SSL для передачи на сервер файла cookie, который используется для кэширования имен ролей.

CookieSlidingExpiration

Получает или задает значение, определяющее периодический сброс файла cookie, который используется для кэширования имен ролей.

CookieTimeout

Получает или задает срок действия файла cookie, который используется для кэширования имен ролей, в минутах.

CreatePersistentCookie

Определяет кэширование имен ролей с использованием сеансовых или постоянных файлов cookie.

CurrentConfiguration

Возвращает ссылку на экземпляр Configuration верхнего уровня, представляющий иерархию конфигурации, к которой относится текущий экземпляр ConfigurationElement.

(Унаследовано от ConfigurationElement)
DefaultProvider

Получает или задает имя поставщика по умолчанию, используемого для управления ролями.

Domain

Получает или задает имя домена, связанного с файлом cookie, который используется для кэширования имен ролей.

ElementInformation

Возвращает объект ElementInformation, содержащий неизменяемую информацию и функциональность объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
ElementProperty

Возвращает объект ConfigurationElementProperty, представляющий сам объект ConfigurationElement.

(Унаследовано от ConfigurationElement)
Enabled

Получает или задает значение, определяющее использование функции управления ролями ASP.NET.

EvaluationContext

Возвращает объект ContextInformation для объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
HasContext

Возвращает значение, указывающее, имеет ли свойство CurrentConfiguration значение null.

(Унаследовано от ConfigurationElement)
Item[ConfigurationProperty]

Возвращает или задает свойство или атрибут данного элемента конфигурации.

(Унаследовано от ConfigurationElement)
Item[String]

Получает или задает свойство, атрибут или дочерний элемент данного элемента конфигурации.

(Унаследовано от ConfigurationElement)
LockAllAttributesExcept

Возвращает коллекцию заблокированных атрибутов.

(Унаследовано от ConfigurationElement)
LockAllElementsExcept

Возвращает коллекцию заблокированных элементов.

(Унаследовано от ConfigurationElement)
LockAttributes

Возвращает коллекцию заблокированных атрибутов.

(Унаследовано от ConfigurationElement)
LockElements

Возвращает коллекцию заблокированных элементов.

(Унаследовано от ConfigurationElement)
LockItem

Возвращает или задает значение, указывающее, заблокирован ли элемент.

(Унаследовано от ConfigurationElement)
MaxCachedResults

Получает или задает максимальное число ролей, которые кэшируются в приложении ASP.NET с использованием файла cookie.

Properties

Возвращает коллекцию свойств.

(Унаследовано от ConfigurationElement)
Providers

Возврат объекта ProviderSettingsCollection элементов ProviderSettings.

SectionInformation

Возвращает объект SectionInformation, содержащий неизменяемую информацию и функциональность объекта ConfigurationSection.

(Унаследовано от ConfigurationSection)

Методы

DeserializeElement(XmlReader, Boolean)

Считывает XML из файла конфигурации.

(Унаследовано от ConfigurationElement)
DeserializeSection(XmlReader)

Считывает XML из файла конфигурации.

(Унаследовано от ConfigurationSection)
Equals(Object)

Сравнивает текущий экземпляр ConfigurationElement с указанным объектом.

(Унаследовано от ConfigurationElement)
GetHashCode()

Получает уникальное значение, представляющее текущий экземпляр ConfigurationElement.

(Унаследовано от ConfigurationElement)
GetRuntimeObject()

Возвращает пользовательский объект при переопределении в производном классе.

(Унаследовано от ConfigurationSection)
GetTransformedAssemblyString(String)

Возвращает преобразованную версию указанного имени сборки.

(Унаследовано от ConfigurationElement)
GetTransformedTypeString(String)

Возвращает преобразованную версию указанного имени типа.

(Унаследовано от ConfigurationElement)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
Init()

Задает объект ConfigurationElement в исходное состояние.

(Унаследовано от ConfigurationElement)
InitializeDefault()

Используется для инициализации набора значений по умолчанию для объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
IsModified()

При реализации в производном классе указывает, был ли изменен данный элемент конфигурации с момента последнего сохранения или загрузки.

(Унаследовано от ConfigurationSection)
IsReadOnly()

Получает значение, показывающее, является ли объект ConfigurationElement доступным только для чтения.

(Унаследовано от ConfigurationElement)
ListErrors(IList)

Добавляет ошибку "недействительное свойство" в данном объекте ConfigurationElement и всех его дочерних элементах к переданному списку.

(Унаследовано от ConfigurationElement)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
OnDeserializeUnrecognizedAttribute(String, String)

Возвращает значение, указывающее, встретился ли неизвестный атрибут при десериализации.

(Унаследовано от ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Возвращает значение, указывающее, встретился ли неизвестный элемент при десериализации.

(Унаследовано от ConfigurationElement)
OnRequiredPropertyNotFound(String)

Выдает исключение, если требуемое свойство не найдено.

(Унаследовано от ConfigurationElement)
PostDeserialize()

Вызывается после десериализации.

(Унаследовано от ConfigurationElement)
PreSerialize(XmlWriter)

Вызывается до сериализации.

(Унаследовано от ConfigurationElement)
Reset(ConfigurationElement)

Восстанавливает внутреннее состояние объекта ConfigurationElement, включая блокировки и коллекции свойств.

(Унаследовано от ConfigurationElement)
ResetModified()

Переустанавливает значение метода IsModified() в false при реализации в производном классе.

(Унаследовано от ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Записывает содержание данного элемента конфигурации в файл конфигурации при реализации в производном классе.

(Унаследовано от ConfigurationElement)
SerializeSection(ConfigurationElement, String, ConfigurationSaveMode)

Создает XML-строку, содержащую разъединенное представление об объекте ConfigurationSection, как об отдельном разделе, записываемым в файл.

(Унаследовано от ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Записывает внешние теги данного элемента конфигурации в файл конфигурации при реализации в производном классе.

(Унаследовано от ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Задает для свойства указанное значение.

(Унаследовано от ConfigurationElement)
SetReadOnly()

Задает свойство IsReadOnly() для объекта ConfigurationElement и всех подчиненных элементов.

(Унаследовано от ConfigurationElement)
ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName)

Указывает, следует ли сериализовать указанный элемент при сериализации иерархии объектов конфигурации для указанной целевой версии платформа .NET Framework.

(Унаследовано от ConfigurationSection)
ShouldSerializePropertyInTargetVersion(ConfigurationProperty, String, FrameworkName, ConfigurationElement)

Указывает, следует ли сериализовать указанное свойство при сериализации иерархии объектов конфигурации для указанной целевой версии платформа .NET Framework.

(Унаследовано от ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Указывает, следует ли сериализовать текущий ConfigurationSection экземпляр при сериализации иерархии объектов конфигурации для указанной целевой версии платформа .NET Framework.

(Унаследовано от ConfigurationSection)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Изменяет объект ConfigurationElement для удаления всех значений, которые не должны сохраняться.

(Унаследовано от ConfigurationElement)

Применяется к

См. также раздел