本文介绍了一个ActionMethodSelectorAttribute适用于所有的行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要适用于所有的动作我的选择,但我不希望它复制并粘贴到处

I want my selector applied to all actions but I don't want to copy and paste it everywhere.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class ActionMethodSelectorAttribute : Attribute

public class VersionAttribute : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        //my logic here
    }
}

GlobalFilterCollection.Add 是不是在这种情况下工作,因为它不是一个 FilterAttribute 。任何想法?

GlobalFilterCollection.Add is not working in this case because it's not a FilterAttribute. Any ideas?

推荐答案

我把这个作为某种挑战 - 试图自定义的 ActionMethodSelector 注入现有的列表。的虽然我还没有发现任何防弹办法做到这一点,我将分享我想出用什么还没有

I took this as some kind of challenge - trying to inject custom ActionMethodSelector into list of existing ones. Though I haven't found any bullet-proof way to do this, I'll share what I've come up with yet

1,创建自定义的 ActionInvoker 并尝试注入选择。我使用的是默认 ReflectedActionDescriptor ,因为它已经包含了的MethodInfo 测试 MyActionMethodSelector 反对。

1.Create custom ActionInvoker and try to inject selector. I used the default ReflectedActionDescriptor, as it already contains MethodInfo to test MyActionMethodSelector against.

public class MyActionInvoker : ControllerActionInvoker
{
    protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
    {
        var action = base.FindAction(controllerContext, controllerDescriptor, actionName);

        if (action != null)
        {
            var reflectedActionDecsriptor = action as ReflectedActionDescriptor;
            if (reflectedActionDecsriptor != null)
            {
                if (new MyActionMethodSelectorAttribute().IsValidForRequest(controllerContext, reflectedActionDecsriptor.MethodInfo))
                {
                    return null;
                }
            }
        }

        return action;
    }
}

2.Inject MyActionInvoker 到控制器。要做到这一点,得到所有控制器,从 MyBaseController ,因为

2.Inject MyActionInvoker into controllers. To do that, derive all of controllers from MyBaseController, implemented as

public class MyBaseController : Controller
{
    protected override IActionInvoker CreateActionInvoker()
    {
        return new MyActionInvoker();
    }
}

这就是它现在:)

这篇关于一个ActionMethodSelectorAttribute适用于所有的行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 18:06