在c#中调用方法时如何执行属性

Ani*_*aha 1 c# asp.net asp.net-mvc custom-attributes system.reflection

我有一个方法.

[AppAuthorize]
public ActionResult StolenCar(object claimContext)
{
    return View("StolenCar");
}
Run Code Online (Sandbox Code Playgroud)

我的属性是这样的代码.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AppAuthorize : Vairs.Presentation.AppAuthorizationAttribute
{
    public bool ConditionalAuthentication
    {
        get;
        set;
    }


    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        bool requireAuthentication = true;

        if (ConditionalAuthentication)
        {

        }

        if (requireAuthentication)
        {
            var appContext = SecurityContext.Current as SitecoreSecurityContext;

            if (appContext != null)
            {
                appContext.LoginPage =  ConfigurationManager.AppSettings[SecurityPaths.Login];
                appContext.LogoffPage = ConfigurationManager.AppSettings[SecurityPaths.Logout];
            }

            if ((appContext != null) && this.RedirectToLogin && !string.IsNullOrEmpty(appContext.LoginPage))
            {
                appContext.RedirectToLogin = true;
            }

            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在c#中动态运行StolenCar方法.

Type magicType = Type.GetType(controllerFullName);
MethodInfo magicMethod = magicType.GetMethod(actionName);
ConstructorInfo magicConstructor =magicType.GetConstructor(Type.EmptyTypes);
object magicClassObject = magicConstructor.Invoke(new object[] { });
var result = magicMethod.Invoke(magicClassObject, new object[] { parameters }) as ActionResult;
return result;
Run Code Online (Sandbox Code Playgroud)

这样我可以调用StolenCar方法,但它不会调用AppAuthorize属性.有没有办法做到这一点?

ang*_*son 5

除了一些内置系统之外,属性并不神奇.

它们只是元数据,附加到类,成员等的额外信息.

如果您希望"执行"这些属性,则必须自己执行此操作.

在你的上下文中,MVC已经为你完成了它所知道的属性,但如果你自己开始调用这些方法,那么你可以在必要时发现并处理这些属性,.NET中的任何内容都不会自动为你做.