检查操作过滤器中的属性 [英] Checking for an attribute in an action filter

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

问题描述

在 MVC 5 中,您可以在 IActionFilter 中执行类似的操作,以检查是否已在当前操作(或在控制器范围内)声明了属性

In MVC 5, you can do something like this inside an IActionFilter, to check if an attribute has been declared on the the current action (or at controller scope)

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    // Stolen from System.Web.Mvc.AuthorizeAttribute
    var isAttributeDefined = filterContext.ActionDescriptor.IsDefined(typeof(CustomAttribute), true) ||
                             filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(CustomAttribute), true);

}

因此,如果您的控制器像这样定义属性,则可以.

So if your controller defines the attribute like so, this works.

[CustomAttribute]
public ActionResult Everything()
{ .. }

是否可以在 ASP.NET Core MVC 中做同样的事情(在 IActionFiler 中)?

Is it possible to do the same in ASP.NET Core MVC (inside an IActionFiler)?

推荐答案

是的,你可以做到.这是 ASP.NET Core 的类似代码.

Yes you can do it. Here is similar code for ASP.NET Core.

public void OnActionExecuting(ActionExecutingContext context)
{
    var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
    if (controllerActionDescriptor != null)
    {
        var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
            .Any(a => a.GetType().Equals(typeof(CustomAttribute)));
    }
}

这篇关于检查操作过滤器中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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