gpt4 book ai didi

c# - 检索 Action 签名自定义属性

转载 作者:行者123 更新时间:2023-11-30 14:55:19 25 4
gpt4 key购买 nike

假设我有一个如下所示的操作方法:

    [return: Safe]
public IEnumerable<string> Get([Safe] SomeData data)
{
return new string[] { "value1", "value2" };
}

[Safe]属性是我自己做的自定义属性。我想创建一个将 [Safe] 属性定位在参数或返回类型上的 ActionFilter。我已经为 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();
}

但是如何检索放置在返回类型上的 [Safe] 属性?

采用这种方法可能会有一些值得探索的东西:

ModelMetadataProvider meta = actionContext.GetMetadataProvider();

但如果这确实有效,目前尚不清楚如何使其与 ModelMetadataProvider 一起使用。

有什么建议吗?

最佳答案

尝试转换 ActionDescriptor 来自 HttpActionContext 的属性(property)至 ReflectedHttpActionDescriptor 第一的。然后使用 MethodInfo 属性通过其 ReturnTypeCustomAttributes 检索您的自定义属性属性(property)。

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<HttpActionDescriptor> 界面:

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();
}
...
}

关于c# - 检索 Action 签名自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com