2010-11-18 46 views
2

是否有一個屬性可以用來限制對方法或程序集的訪問?如何限制對方法的訪問,只允許特定程序集訪問它們?

(我正在使用C#,.Net 3.5)

例如

[RestrictionAttribute(//Specify an assembly or a key or something here)] 
Public void MyMethod() 
{ 
    //Do something... 
} 

我要上的一些業務組件,其中一些認證等均可發生,要確保業務組件不能只通過訪問直接訪問,頂部添加代碼的「接入層」層。

回答

3

對於您的課程,您可以使用internal關鍵字代替public,然後使用InternalsVisibleTo屬性。

托馬斯

2

不使用屬性,你可以這樣做:

using System.Reflection; 
using System.Security; 

protected const string AUTHORIZED_CALLER 
    = "YourTrustedAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7bb5a56c4391e80f"; 

public void MyMethod() 
{ 
    if (Assembly.GetCallingAssembly().FullName != AUTHORIZED_CALLER) { 
     throw new SecurityException("Unauthorized method call."); 
    } 

    // Now do something. 
} 
相關問題