Anik Saha
Anik Saha

Reputation: 4494

How to execute an attribute when invoking a method in c#

I have a method.

[AppAuthorize]
public ActionResult StolenCar(object claimContext)
{
    return View("StolenCar");
}

My attribute is code something like this.

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

I want to run StolenCar method dynamically in c#.

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;

This way I can invoke StolenCar Method but it does not call AppAuthorize Attribute. Is there any way to do that ?

Upvotes: 1

Views: 1364

Answers (2)

SBFrancies
SBFrancies

Reputation: 4240

You may want to try inheriting from ActionFilterAttribute and overriding the OnActionExecuting method:

public class YourAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);

        //Your code goes here
    }
}

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391396

Apart from a few built-in system ones, attributes are not magical.

They're simply meta-data, extra information attached to a class, member, etc.

If you want these attributes to be "executed", you will have to do so yourself.

In your context, MVC already does this for you, for the attributes it knows about, but if you start calling these methods yourself then it's on you to discover and process these attributes if necessary, nothing in .NET will do it for you automagically.

Upvotes: 5

Related Questions