![](/img/trans.png)
[英]Get Attribute from object; 'Attribute' does not contain a definition for 'GetCustomAttribute'
[英]C# - Custom Attribute not found from GetCustomAttribute from Interface
我正在嘗試設置如下自定義屬性:
[AttributeUsageAttribute(AttributeTargets.Method)]
public sealed class AuthorizationAttribute : Attribute
{
public AuthorizationAttribute(bool required)
{
Required = required;
}
public bool Required;
}
在我的服務合同界面中,我有一個這樣的方法:
[OperationContract]
[Authorization(true)]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "randommethod")]
ReturnObject RandomMethod();
當我執行以下操作時,我會在列表中看到它,但是'是'比較,失敗:
foreach(object attribute in methodInfo.GetCustomAttributes(true)) // Returns all 3 of my attributes.
if (attribute is AuthorizationAttribute) //Does not pass
我試圖做以下返回false:
Attribute.IsDefined(methodInfo, typeof(AuthorizationAttribute));
attribute.GetType().IsAssignableFrom(typeof(AuthorizationAttribute));
我還做了以下兩件返回null的事情:
AuthorizationAttribute authAttribute = attribute as AuthorizationAttribute;
Attribute attribute = Attribute.GetCustomAttribute(methodInfo, typeof(AuthorizationAttribute));
我不確定我在這里做錯了什么。 看起來它應該可行,但我確信我在某個地方犯了一個簡單的錯誤。 任何見解?
謝謝你的幫助。
編輯:我不確定它是否添加任何含義,但AuthorizationAttribute聲明存在於與我的服務項目不同的項目中。 Service Contract接口與AuthorizationAttribute存在於同一項目中。
我嘗試做一個演員並得到以下異常:
[A]Lib.OAuth.AuthorizationAttribute cannot be cast to [B]Lib.OAuth.AuthorizationAttribute.
Type A originates from 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the
context 'LoadNeither' at location 'F:\RestServices\bin\Lib.dll'. Type B originates from 'Lib,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location
'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\oauth_rest\951069b9
\9f7b77fe\assembly\dl3\54c48906\f928a6ad_01facb01\Lib.dll'.
有任何想法嗎?
例外包含答案:
類型A發起...位於'F:\\ RestServices \\ bin \\ Lib.dll'。 類型B發起...位於'C:\\ Windows \\ Microsoft.NET \\ Framework64 \\ v4.0.30319 \\ Temporary ASP.NET Files \\ oauth_rest \\ 951069b9 \\ 9f7b77fe \\ assembly \\ dl3 \\ 54c48906 \\ f928a6ad_01facb01 \\ Lib.dll'
問題是,在您Lib.OAuth.AuthorizationAttribute
,在程序Lib.OAuth.AuthorizationAttribute
找到屬於您的方法的Lib.OAuth.AuthorizationAttribute
類型,該程序集與運行時加載的程序集不同。
您的某個項目是否可能使用舊版本的Lib.dll?
感謝韋斯利的回應,我能夠解決這個問題。 它比任何事情都更像是一個'呃'。
我使用一些示例代碼進行反射,以通過Assembly.LoadFile(...)方法加載程序集。 問題是,由於我的程序集未在GAC中注冊,因此它正在讀取IIS服務器上的本地副本,並且比較失敗。
作為參考,這是我的解決方案:
Assembly.GetExecutingAssembly();
一旦我這樣做,一切都有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.