我试图建立一个自定义的发现属性如下所示: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'.
任何想法?
你肯定'methodInfo'指的是正确的方法? – Ani 2011-04-13 17:12:14
是的,因为当我调用methodInfo.GetCustomAttributes(true)时,它将返回所有3个属性。出于某种原因,我无法将该数组中的AuthorizationAttribute转换为我的AuthorizationAttribute的实例。 – Brandon 2011-04-13 17:16:09
您是否可以尝试执行attribute.GetType().GetName()以查看在调试时看到的属性的运行时类型? – 2011-04-13 17:25:07