我正在尝试设置一个自定义属性,如下所示:
[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();当我执行以下操作时,我在列表中看到它,但'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声明存在于与我的服务项目不同的项目中。服务契约接口与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'.有什么想法吗?
发布于 2011-04-14 03:35:21
多亏了Wesley的回应,我才能弄明白这一点。这比任何事情都更像是一个“废话”时刻。
我使用了一些反射示例代码来通过Assembly.LoadFile(...)加载程序集。方法。问题是,由于我的程序集没有在GAC中注册,它正在读取IIS服务器上的本地副本,比较失败。
作为参考,这是我的解决方案:
Assembly.GetExecutingAssembly();一旦我这样做了,一切都正常了。
发布于 2011-04-14 01:56:10
异常包含答案:
RestServices类型
位置‘F:\ originates...at \bin\lib.dll’。Type originates...at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary Files\oauth_rest\951069b9 Files\oauth_rest\951069b9类型
问题是,当您尝试强制转换时,会在与运行时加载的程序集不同的程序集中找到属于您的方法的Lib.OAuth.AuthorizationAttribute类型。
有没有可能您的某个项目正在使用旧版本的Lib.dll?
https://stackoverflow.com/questions/5652846
复制相似问题