控制器方法上的MVC中间件检查属性 [英] MVC middleware check attribute on controller method

查看:74
本文介绍了控制器方法上的MVC中间件检查属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net core mvc.在默认身份验证旁边,我添加了非常具体的授权,该授权通过使用ResultFilterAttribute属性完成.

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.

可以在MVC中间件中完成吗?还是有更好的方法?

Can it be done in MVC middleware. Or maybe there is better approach?

推荐答案

感谢 Christian 提及了.就我而言,这是正确的方法.

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

在Startup.cs,在解析IControllerFactory接口时,需要告诉mvc使用MyControllerFactory.

At at Startup.cs need to tell mvc to use MyControllerFactory when resolving IControllerFactory interface.

services.AddSingleton<IControllerFactory, MyControllerFactory>();

这篇关于控制器方法上的MVC中间件检查属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆