![](/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.