共用方式為


使用安全性使用權限驗證 ADO.NET 程式碼存取

對部份信任案例來說,您可以在程式碼中指定必要的 SqlClientPermissionAttribute 屬性,將特定的方法指定為需要特定的程式碼存取安全性權限。如果您的程式碼中不允許這個權限,則執行程式碼前會擲回例外狀況。

**注意   **由於部份信任案例未啟用 OLE DB 的 .NET Framework 資料提供者和 ODBC 的 .NET Framework 資料提供者,所以特定權限測試也許會成功,但是執行程式碼時,將會因 SecurityException 而失敗。

例如,下列程式碼顯示指定要求特定連接字串的方法。如果不允許這個連接字串,則會擲回例外狀況,而且不執行這個方法。

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Security
Imports System.Security.Permissions

Public Class Sample

  <SqlClientPermissionAttribute(SecurityAction.Demand, ConnectionString := " Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")> _
  Private Shared Sub OpenConn()
    Dim testConn As SqlConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")
    testConn.Open()
    Console.WriteLine("The calling method has been granted sufficient permission to access the database.")
    testConn.Close()
  End Sub

  Public Shared Sub Main() 
    Try
      OpenConn()
    Catch e As SecurityException
      Console.WriteLine("The calling method has not been granted sufficient permission to access the database.")
    End Try
  End Sub
End Class
[C#]
using System;
using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Security.Permissions;

public class Sample
{

  [SqlClientPermissionAttribute(SecurityAction.Demand, ConnectionString = " Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")]
  private static void OpenConn()
  {
    SqlConnection testConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");
    testConn.Open();
    Console.WriteLine("The calling method has been granted sufficient permission to access the database.");
    testConn.Close();
  }

  public static void Main() 
  {
    try
    {
      OpenConn();
    }
    catch (SecurityException)
    {
      Console.WriteLine("The calling method has not been granted sufficient permission to access the database.");
    }
  }
}

請參閱

撰寫安全 ADO.NET 程式碼 | 程式碼存取安全性