c# -从接口的GetCustomAttribute中找不到自定义属性

本文关键字:找不到 自定义属性 GetCustomAttribute 接口 | 更新日期: 2023-09-27 17:49:56

我试图设置一个自定义属性,如下所示:

[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();

当我执行以下操作时,我在列表中看到它,但是but 'is'比较失败:

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'.

任何想法?

c# -从接口的GetCustomAttribute中找不到自定义属性

异常包含答案:

A型起源于…在位置'F:'RestServices'bin'Lib.dll'。B型源于……在位置"C: ' Windows ' Microsoft.NET ' Framework64 ' v4.0.30319 '临时ASP。网络文件' oauth_rest ' 951069 b9' 9 f7b77fe '会议' dl3 ' 54 c48906 ' f928a6ad_01facb01 ' Lib.dll"

问题是,Lib.OAuth.AuthorizationAttribute类型的属性你的方法是在一个不同的程序集中发现的,而不是在运行时加载的程序集,当你试图转换。

是否有可能你的一个项目正在使用旧版本的Lib.dll?

多亏了Wesley的回复,我才弄明白了这一点。这更像是一个"duh"时刻。

我正在使用一些反射示例代码,通过assembly . loadfile(…)方法加载程序集。问题是,由于我的程序集没有向GAC注册,因此它正在读取IIS服务器上的本地副本,并且比较失败。

作为参考,这是我的解决方案:

Assembly.GetExecutingAssembly();

一旦我这样做了,一切都工作了。