GlobalizationSection Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет параметры конфигурации, используемые для поддержки инфраструктуры глобализации веб-приложений. Этот класс не наследуется.
public ref class GlobalizationSection sealed : System::Configuration::ConfigurationSection
public sealed class GlobalizationSection : System.Configuration.ConfigurationSection
type GlobalizationSection = class
inherit ConfigurationSection
Public NotInheritable Class GlobalizationSection
Inherits ConfigurationSection
- Наследование
Примеры
В этом примере показано, как декларативно указать значения для нескольких атрибутов globalization раздела, к которым также можно обращаться как к членам GlobalizationSection класса .
В следующем примере файла конфигурации показано, как декларативно указать значения для globalization раздела.
<system.web>
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"/>
</system.web>
В следующем примере кода показано, как использовать GlobalizationSection класс .
#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 UsingGlobalizationSection
{
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.
GlobalizationSection configSection =
(GlobalizationSection)config.GetSection("system.web/globalization");
// 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 Culture property.
Console.WriteLine("Culture: {0}",
configSection.Culture);
// Set Culture property.
configSection.Culture =
System.Globalization.CultureInfo.CurrentCulture.ToString();
// Display EnableClientBasedCulture property.
Console.WriteLine("EnableClientBasedCulture: {0}",
configSection.EnableClientBasedCulture);
// Set EnableClientBasedCulture property.
configSection.EnableClientBasedCulture = false;
// Display FileEncoding property.
Console.WriteLine("FileEncoding: {0}",
configSection.FileEncoding);
// Set FileEncoding property.
configSection.FileEncoding =
System.Text.Encoding.UTF8;
// Display RequestEncoding property.
Console.WriteLine("RequestEncoding: {0}",
configSection.RequestEncoding);
// Set RequestEncoding property.
configSection.RequestEncoding =
System.Text.Encoding.UTF8;
// Display ResponseEncoding property.
Console.WriteLine("ResponseEncoding: {0}",
configSection.ResponseEncoding);
// Set ResponseEncoding property.
configSection.ResponseEncoding =
System.Text.Encoding.UTF8;
// Display ResponseHeaderEncoding property.
Console.WriteLine("ResponseHeaderEncoding: {0}",
configSection.ResponseHeaderEncoding);
// Set ResponseHeaderEncoding property.
configSection.ResponseHeaderEncoding =
System.Text.Encoding.UTF8;
// Display UICulture property.
Console.WriteLine("UICulture: {0}",
configSection.UICulture);
// Set UICulture property.
configSection.UICulture =
System.Globalization.CultureInfo.CurrentUICulture.ToString();
// 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 UsingGlobalizationSection
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 = _
WebConfigurationManager.OpenWebConfiguration(configPath)
' Get the section related object.
Dim configSection As System.Web.Configuration.GlobalizationSection = _
CType(config.GetSection("system.web/globalization"), _
System.Web.Configuration.GlobalizationSection)
' 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 Culture property.
Console.WriteLine("Culture: {0}", _
configSection.Culture)
' Set Culture property.
configSection.Culture = _
System.Globalization.CultureInfo.CurrentCulture.ToString()
' Display EnableClientBasedCulture property.
Console.WriteLine("EnableClientBasedCulture: {0}", _
configSection.EnableClientBasedCulture)
' Set EnableClientBasedCulture property.
configSection.EnableClientBasedCulture = False
' Display FileEncoding property.
Console.WriteLine("FileEncoding: {0}", _
configSection.FileEncoding)
' Set FileEncoding property.
configSection.FileEncoding = _
System.Text.Encoding.UTF8
' Display RequestEncoding property.
Console.WriteLine("RequestEncoding: {0}", _
configSection.RequestEncoding)
' Set RequestEncoding property.
configSection.RequestEncoding = _
System.Text.Encoding.UTF8
' Display ResponseEncoding property.
Console.WriteLine("ResponseEncoding: {0}", _
configSection.ResponseEncoding)
' Set ResponseEncoding property.
configSection.ResponseEncoding = _
System.Text.Encoding.UTF8
' Display ResponseHeaderEncoding property.
Console.WriteLine("ResponseHeaderEncoding: {0}", _
configSection.ResponseHeaderEncoding)
' Set ResponseHeaderEncoding property.
configSection.ResponseHeaderEncoding = _
System.Text.Encoding.UTF8
' Display UICulture property.
Console.WriteLine("UICulture: {0}", _
configSection.UICulture)
' Set UICulture property.
configSection.UICulture = _
System.Globalization.CultureInfo.CurrentUICulture.ToString()
' 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
Комментарии
Класс GlobalizationSection предоставляет способ программного доступа и изменения содержимого globalization раздела файла конфигурации.
Конструкторы
| GlobalizationSection() |
Инициализирует новый экземпляр класса GlobalizationSection с использованием параметров по умолчанию. |
Свойства
| Culture |
Получает или задает значение, указывающее язык и региональные параметры по умолчанию для обработки входящих веб-запросов. |
| CurrentConfiguration |
Возвращает ссылку на экземпляр Configuration верхнего уровня, представляющий иерархию конфигурации, к которой относится текущий экземпляр ConfigurationElement. (Унаследовано от ConfigurationElement) |
| ElementInformation |
Возвращает объект ElementInformation, содержащий неизменяемую информацию и функциональность объекта ConfigurationElement. (Унаследовано от ConfigurationElement) |
| ElementProperty |
Возвращает объект ConfigurationElementProperty, представляющий сам объект ConfigurationElement. (Унаследовано от ConfigurationElement) |
| EnableBestFitResponseEncoding |
Получает или задает значение, указывающее на то, активирована ли наиболее подходящая кодировка для ответа. |
| EnableClientBasedCulture |
Получает или задает значение, указывающее на то, должны ли свойства Culture и UICulture быть основаны на значении поля заголовка AcceptLanguage, отправленного клиентским браузером. |
| EvaluationContext |
Возвращает объект ContextInformation для объекта ConfigurationElement. (Унаследовано от ConfigurationElement) |
| FileEncoding |
Получает или задает значение, указывающее кодировку по умолчанию для синтаксического анализа файлов ".aspx", ".asmx" и ".asax". |
| HasContext |
Возвращает значение, указывающее, имеет ли свойство CurrentConfiguration значение |
| Item[ConfigurationProperty] |
Возвращает или задает свойство или атрибут данного элемента конфигурации. (Унаследовано от ConfigurationElement) |
| Item[String] |
Получает или задает свойство, атрибут или дочерний элемент данного элемента конфигурации. (Унаследовано от ConfigurationElement) |
| LockAllAttributesExcept |
Возвращает коллекцию заблокированных атрибутов. (Унаследовано от ConfigurationElement) |
| LockAllElementsExcept |
Возвращает коллекцию заблокированных элементов. (Унаследовано от ConfigurationElement) |
| LockAttributes |
Возвращает коллекцию заблокированных атрибутов. (Унаследовано от ConfigurationElement) |
| LockElements |
Возвращает коллекцию заблокированных элементов. (Унаследовано от ConfigurationElement) |
| LockItem |
Возвращает или задает значение, указывающее, заблокирован ли элемент. (Унаследовано от ConfigurationElement) |
| Properties |
Возвращает коллекцию свойств. (Унаследовано от ConfigurationElement) |
| RequestEncoding |
Получает или задает значение, указывающее кодировку содержимого HTTP-запросов. |
| ResourceProviderFactoryType |
Получает или задает тип производства поставщика ресурсов. |
| ResponseEncoding |
Получает или задает значение, указывающее кодировку содержимого HTTP-ответов. |
| ResponseHeaderEncoding |
Получает или задает значение, указывающее кодировку заголовка HTTP-ответов. |
| SectionInformation |
Возвращает объект SectionInformation, содержащий неизменяемую информацию и функциональность объекта ConfigurationSection. (Унаследовано от ConfigurationSection) |
| UICulture |
Получает или задает значение, указывающее язык и региональные параметры по умолчанию для обработки операций поиска ресурсов, зависимых от языковых стандартов. |
Методы
| 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() в |
| 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) |