共用方式為


CA2234:必須傳遞 System.Uri 物件,而不要傳遞字串

型別名稱

PassSystemUriObjectsInsteadOfStrings

CheckId

CA2234

分類

Microsoft.Usage

中斷變更

不中斷

原因

呼叫字串參數名稱包含 "uri"、"Uri"、"urn"、"Urn"、"url" 或 "Url" 的方法,而且此方法的宣告型別會包含具有 System.Uri 參數的對應方法多載。

規則描述

參數名稱會根據 Camel 命名法的大小寫慣例而分割為兩個語彙基元 (Token),而且會檢查每個語彙基元是否等於 "uri"、"Uri"、"urn"、"Urn"、"url" 或 "Url"。 如果沒有相符者,則假設參數代表統一資源識別元 (URI)。 URI 的字串表示方式容易發生剖析和編碼錯誤,並且可能因此產生安全性弱點。 Uri 類別以安全的方式提供這些服務。 在僅有 URI 表示不同的兩個多載間進行選擇時,使用者應該選擇採用 Uri 引數的多載。

如何修正違規

若要修正此規則的違規情形,請呼叫採用 Uri 引數的多載。

隱藏警告的時機

如果字串參數不代表 URI,則您可以放心地隱藏這項規則的警告。

範例

下列範例會顯示違反規則的方法 (ErrorProne),以及正確呼叫 Uri 多載的方法 (SaferWay)。

Imports System

Namespace DesignLibrary

   Class History

      Friend Sub AddToHistory(uriString As String)
      End Sub

      Friend Sub AddToHistory(uriType As Uri)
      End Sub

   End Class

   Public Class Browser

      Dim uriHistory As New History()

      Sub ErrorProne()
         uriHistory.AddToHistory("https://www.adventure-works.com")
      End Sub

      Sub SaferWay()
         Try
            Dim newUri As New Uri("https://www.adventure-works.com")
            uriHistory.AddToHistory(newUri)
         Catch uriException As UriFormatException
         End Try
      End Sub

   End Class

End Namespace
using System;

namespace DesignLibrary
{
   class History
   {
      internal void AddToHistory(string uriString) {}
      internal void AddToHistory(Uri uriType) {}
   }

   public class Browser
   {
      History uriHistory = new History();

      public void ErrorProne()
      {
         uriHistory.AddToHistory("https://www.adventure-works.com");
      }

      public void SaferWay()
      {
         try
         {
            Uri newUri = new Uri("https://www.adventure-works.com");
            uriHistory.AddToHistory(newUri);
         }
         catch(UriFormatException uriException) {}
      }
   }
}
#using <system.dll>
using namespace System;

namespace DesignLibrary
{
   ref class History
   {
   public:
      void AddToHistory(String^ uriString) {}
      void AddToHistory(Uri^ uriType) {}
   };

   public ref class Browser
   {
      History^ uriHistory;

   public:
      Browser()
      {
         uriHistory = gcnew History();
      }

      void ErrorProne()
      {
         uriHistory->AddToHistory("https://www.adventure-works.com");
      }

      void SaferWay()
      {
         try
         {
            Uri^ newUri = gcnew Uri("https://www.adventure-works.com");
            uriHistory->AddToHistory(newUri);
         }
         catch(UriFormatException^ uriException) {}
      }
   };
}

相關規則

CA1057:字串 URI 多載呼叫 System.Uri 多載

CA1056:URI 屬性不應該為字串

CA1054:URI 參數不應該為字串

CA1055:URI 傳回值不應該為字串