问题
I am using asp.net core mvc. Next to default authentification I have added very specific authorization which is done by using ResultFilterAttribute
attribute.
In future, to make sure that developers are going to specify permissions for each controller method I would like to check if the attribute is set for method, before action is executed.
Can it be done in MVC middleware. Or maybe there is better approach?
回答1:
Thanks to Christian for mentioning ControllerFactory
. It was right approach in my case.
public class MyControllerFactory : DefaultControllerFactory
{
public MyControllerFactory (IControllerActivator controllerActivator, IEnumerable<IControllerPropertyActivator> propertyActivators)
: base(controllerActivator, propertyActivators)
{
}
public override object CreateController(ControllerContext context)
{
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(PermissionFilterAttribute)));
if (!isDefined)
{
throw new NotImplementedException();
}
return base.CreateController(context);
}
}
At at Startup.cs need to tell mvc to use MyControllerFactory when resolving IControllerFactory interface.
services.AddSingleton<IControllerFactory, MyControllerFactory>();
来源:https://stackoverflow.com/questions/44242885/mvc-middleware-check-attribute-on-controller-method