【问题标题】:How to execute an attribute when invoking a method in c#在c#中调用方法时如何执行属性
【发布时间】:2018-06-23 21:19:00
【问题描述】:

我有一个方法。

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

我的属性是这样的代码。

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

我想在 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;

这样我可以调用 StolenCar 方法但它不会调用 AppAuthorize 属性。有什么办法吗?

【问题讨论】:

  • 只要new Class().StolenCar(null)。属性仅由 MVC 框架执行。
  • “执行属性”是什么意思。属性主要用于指示某事,它们通常没有太多逻辑,尤其是没有业务逻辑。
  • 你在Vairs.Presentation.AppAuthorizationAttribute类中使用AuthorizeAttribute吗?
  • 是的 AppAuthorizationAttribute 类正在扩展 System.Web.Mvc.AuthorizeAttribute@stom

标签: c# asp.net asp.net-mvc custom-attributes system.reflection


【解决方案1】:

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

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

如果您希望“执行”这些属性,则必须自己执行。

在您的上下文中,MVC 已经为您完成了这项工作,因为它知道的属性,但是如果您自己开始调用这些方法,那么您需要发现和处理这些属性如果需要,什么都没有在 .NET 中会自动为您完成。

【讨论】:

  • 从技术上讲,MVC 不会“执行属性”,它会执行恰好在与属性相同的类中实现的过滤器(尽管它执行类的不同实例 )。如果它有助于减少混淆,可以将过滤器和属性分离到它们自己的类中,如Passive Attributes
  • 因此我在引号中写了“执行”。
【解决方案2】:

您可能想尝试从ActionFilterAttribute 继承并覆盖OnActionExecuting 方法:

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

        //Your code goes here
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2021-06-09
    相关资源
    最近更新 更多