【发布时间】:2020-02-06 07:35:28
【问题描述】:
使用 .NET Core 2.1。
我正在尝试访问 IAsyncActionFilter 内的 action 参数的属性。
public IActionResult DoSomething([MyAttribute] MyParameter p) { ... }
在我的 IAsyncActionFilter 中,我想访问参数 p 上的 MyAttribute,但 GetCustomAttributes 不存在。
public class MyActionFilter : IAsyncActionFilter
{
public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// GetCustomAttributes does not exist here...
var attributes = context.ActionDescriptor.Parameters[0].GetCustomAttributes<MyAttribute>();
return next();
}
}
在 ASP.NET MVC 5.2 中,您可以使用 GetCustomAttributes:
在 .NET Core 中实现相同的方法是什么?
更新 1
似乎我们可以将 ActionDescriptor 转换为 ControllerActionDescriptor 以访问底层 MethodInfo,然后访问参数及其属性。
public class TempDataActionFilter : IAsyncActionFilter
{
public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var actionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
var parameters =
from p in actionDescriptor.MethodInfo.GetParameters()
where p.GetCustomAttributes(typeof(MyAttribute), true) != null
select p;
var controller = context.Controller as Controller;
foreach (var p in parameters)
{
// Do something with the parameters that have an attribute
}
return next();
}
}
这感觉不对。看到微软自己的文档中提出了这种类型的解决方案,我总是感到沮丧。这是一个等待发生的运行时错误。有没有更好的办法?
【问题讨论】:
标签: c# asp.net-core .net-core asp.net-core-webapi asp.net-core-2.1