CA2123: запросы компоновки переопределения должны быть идентичны базовым

Товар Значение
Идентификатор правила CA2123
Категория Microsoft.Security
Критическое изменение Критическое

Причина

Общедоступный или защищенный метод в общедоступном типе переопределяет метод или реализует интерфейс и не имеет одинаковых требований link, что и интерфейс или виртуальный метод.

Примечание.

Это правило устарело. Дополнительные сведения см. в разделе "Устаревшие правила".

Описание правила

Это правило сравнивает метод с его базовым методом (который является интерфейсом или виртуальным методом другого типа), а затем сравнивает запросы ссылок для каждого из них. Сообщается о нарушении, если метод или базовый метод имеют требование ссылки, а другой — нет.

Если это правило нарушается, злоумышленник может обойти требование ссылки только путем вызова незащищенного метода.

Устранение нарушений

Чтобы устранить нарушение этого правила, примените тот же запрос ссылки к методу или реализации переопределения. Если это невозможно, пометьте метод с полным спросом или удалите атрибут полностью.

Когда лучше отключить предупреждения

Для этого правила отключать вывод предупреждений не следует.

Пример

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

using System.Security;
using System.Security.Permissions;
using System;

namespace SecurityRulesLibrary
{
   public interface ITestOverrides
   {  
      [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
      Object GetFormat(Type formatType);
   }

   public class OverridesAndSecurity : ITestOverrides
   {
      // Rule violation: The interface has security, and this implementation does not.
      object ITestOverrides.GetFormat(Type formatType)
      {
         return (formatType == typeof(OverridesAndSecurity) ? this : null);
      }

      // These two methods are overridden by DerivedClass and DoublyDerivedClass.
      [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
      public virtual void DoSomething()
      {
         Console.WriteLine("Doing something.");
      }

      public virtual void DoSomethingElse()
      {
         Console.WriteLine("Doing some other thing.");
      }
   }

   public class DerivedClass : OverridesAndSecurity, ITestOverrides
   {
      //  Rule violation: The interface has security, and this implementation does not.
      public object GetFormat(Type formatType)
      {
         return (formatType == typeof(OverridesAndSecurity) ? this : null);
      }

      // Rule violation: This does not have security, but the base class version does.
      public override void DoSomething()
      {
         Console.WriteLine("Doing some derived thing.");
      }

      // Rule violation: This has security, but the base class version does not.
      [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
      public override void DoSomethingElse()
      {
         Console.WriteLine("Doing some other derived thing.");
      }
   }

   public class DoublyDerivedClass : DerivedClass
   {
      // The OverridesAndSecurity version of this method does not have security. 
      // Base class DerivedClass's version does. 
      // The DoublyDerivedClass version does not violate the rule, but the 
      // DerivedClass version does violate the rule.
      public override void DoSomethingElse()
      {
         Console.WriteLine("Doing some other derived thing.");
      }
   }
}

См. также