Using .NET Core 2.1.
I am trying to access the attributes on the action parameter inside of an IAsyncActionFilter.
public IActionResult DoSomething([MyAttribute] MyParameter p) { ... }
In my IAsyncActionFilter, I would like to access the MyAttribute on the parameter p, but GetCustomAttributes does not exist.
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();
}
}
In ASP.NET MVC 5.2, you can use GetCustomAttributes:
What is the way to achieve the same in .NET Core?
UPDATE 1
It seems we can cast the ActionDescriptor to ControllerActionDescriptor to access the underlying MethodInfo and then the parameters and their attributes.
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();
}
}
This feels wrong. I am always dismayed to see solutions of this type being proposed in Microsoft's own documentation. This is a runtime error waiting to happen. Is there a better way?