假设我有一个类似下面这样的action方法:
[return: Safe]
public IEnumerable<string> Get([Safe] SomeData data)
{
return new string[] { "value1", "value2" };
}Safe属性是我创建的自定义属性。我想创建一个ActionFilter,它在参数或返回类型上定位Safe属性。我已经对OnActionExecuting覆盖中的参数起作用了,因为我可以像这样访问我的Safe属性:
//actionContext is of type HttpActionContext and is a supplied parameter.
foreach (var parm in actionContext.ActionDescriptor.ActionBinding.ParameterBindings)
{
var safeAtts = parm.Descriptor.GetCustomAttributes<SafeAttribute>().ToArray();
}但是如何检索放在返回类型上的安全属性呢?
通过采用这种方法,可能会有一些东西需要探索:
ModelMetadataProvider meta = actionContext.GetMetadataProvider();但如果这真的有效,目前还不清楚如何让它与ModelMetadataProvider一起工作。
有什么建议吗?
发布于 2014-09-05 12:57:26
尝试首先将ActionDescriptor属性从HttpActionContext转换为ReflectedHttpActionDescriptor。然后使用MethodInfo属性通过其ReturnTypeCustomAttributes属性检索您的自定义属性。
public override void OnActionExecuting(HttpActionContext actionContext)
{
...
var reflectedActionDescriptor = actionContext.ActionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
// get the custom attributes applied to the action return value
var attrs = reflectedActionDescriptor
.MethodInfo
.ReturnTypeCustomAttributes
.GetCustomAttributes(typeof (SafeAttribute), false)
.OfType<SafeAttribute>()
.ToArray();
}
...
}更新:已启用跟踪
ActionDescriptor的具体类型似乎取决于Global Web API Services是否包含ITraceWriter的实例(参见:Tracing in ASP.NET Web API)。
默认情况下,ActionDescriptor的类型为ReflectedHttpActionDescriptor。但是当启用跟踪时-通过调用config.EnableSystemDiagnosticsTracing()- ActionDescriptor将被包装在HttpActionDescriptorTracer类型中
为了解决这个问题,我们需要检查ActionDescriptor是否实现了IDecorator接口:
public override void OnActionExecuting(HttpActionContext actionContext)
{
...
ReflectedHttpActionDescriptor reflectedActionDescriptor;
// Check whether the ActionDescriptor is wrapped in a decorator or not.
var wrapper = actionContext.ActionDescriptor as IDecorator<HttpActionDescriptor>;
if (wrapper != null)
{
reflectedActionDescriptor = wrapper.Inner as ReflectedHttpActionDescriptor;
}
else
{
reflectedActionDescriptor = actionContext.ActionDescriptor as ReflectedHttpActionDescriptor;
}
if (reflectedActionDescriptor != null)
{
// get the custom attributes applied to the action return value
var attrs = reflectedActionDescriptor
.MethodInfo
.ReturnTypeCustomAttributes
.GetCustomAttributes(typeof (SafeAttribute), false)
.OfType<SafeAttribute>()
.ToArray();
}
...
}https://stackoverflow.com/questions/25676192
复制相似问题