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

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

问题描述

在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天全站免登陆