2011-04-13 45 views
8

我试图建立一个自定义的发现属性如下所示:C# - 自定义属性不是从GetCustomAttribute从接口

[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如下:我不知道我在做什么错在这里

AuthorizationAttribute authAttribute = attribute as AuthorizationAttribute; 
Attribute attribute = Attribute.GetCustomAttribute(methodInfo, typeof(AuthorizationAttribute)); 

Attribute.IsDefined(methodInfo, typeof(AuthorizationAttribute)); 
attribute.GetType().IsAssignableFrom(typeof(AuthorizationAttribute)); 

我也做了以下两件事情是返回null。它似乎应该工作,但我相信我在某个地方犯了一个简单的错误。任何见解?

感谢您的任何帮助。

编辑: 我不确定它是否增加了任何意义,但AuthorizationAttribute声明存在于与我的服务项目不同的项目中。服务合同界面与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'. 

任何想法?

+0

你肯定'methodInfo'指的是正确的方法? – Ani 2011-04-13 17:12:14

+0

是的,因为当我调用methodInfo.GetCustomAttributes(true)时,它将返回所有3个属性。出于某种原因,我无法将该数组中的AuthorizationAttribute转换为我的AuthorizationAttribute的实例。 – Brandon 2011-04-13 17:16:09

+0

您是否可以尝试执行attribute.GetType().GetName()以查看在调试时看到的属性的运行时类型? – 2011-04-13 17:25:07

回答

1

由于韦斯利的反应,我能想出解决办法。这比任何事情都更像是一个'唔'的时刻。

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

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

Assembly.GetExecutingAssembly(); 

一旦我做到了,一切正常。

5

的异常包含了答案:

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.dll的?