Bra*_*don 8 .net c# reflection attributes
我正在尝试设置如下自定义属性:
[AttributeUsageAttribute(AttributeTargets.Method)]
public sealed class AuthorizationAttribute : Attribute
{
public AuthorizationAttribute(bool required)
{
Required = required;
}
public bool Required;
}
Run Code Online (Sandbox Code Playgroud)
在我的服务合同界面中,我有一个这样的方法:
[OperationContract]
[Authorization(true)]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "randommethod")]
ReturnObject RandomMethod();
Run Code Online (Sandbox Code Playgroud)
当我执行以下操作时,我会在列表中看到它,但是'是'比较,失败:
foreach(object attribute in methodInfo.GetCustomAttributes(true)) // Returns all 3 of my attributes.
if (attribute is AuthorizationAttribute) //Does not pass
Run Code Online (Sandbox Code Playgroud)
我试图做以下返回false:
Attribute.IsDefined(methodInfo, typeof(AuthorizationAttribute));
attribute.GetType().IsAssignableFrom(typeof(AuthorizationAttribute));
Run Code Online (Sandbox Code Playgroud)
我还做了以下两件返回null的事情:
AuthorizationAttribute authAttribute = attribute as AuthorizationAttribute;
Attribute attribute = Attribute.GetCustomAttribute(methodInfo, typeof(AuthorizationAttribute));
Run Code Online (Sandbox Code Playgroud)
我不确定我在这里做错了什么.看起来它应该可行,但我确信我在某个地方犯了一个简单的错误.任何见解?
谢谢你的帮助.
编辑:我不确定它是否添加任何含义,但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'.
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
例外包含答案:
类型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?
感谢韦斯利的回应,我才明白了这一点。这更像是一个“呃”时刻。
我使用一些示例代码进行反射,通过 Assembly.LoadFile(...) 方法加载程序集。问题是,由于我的程序集未向 GAC 注册,它正在读取 IIS 服务器上的本地副本,并且比较失败。
作为参考,这是我的解决方案:
Assembly.GetExecutingAssembly();
Run Code Online (Sandbox Code Playgroud)
一旦我这样做了,一切就都成功了。
| 归档时间: |
|
| 查看次数: |
6629 次 |
| 最近记录: |