MVC middleware check attribute on controller method

ぐ巨炮叔叔 提交于 2019-12-24 05:55:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!