asp.net-mvc 获取 ASP.NET MVC 中当前操作/控制器的自定义属性列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3569317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:26:14  来源:igfitidea点击:

Get list of custom attributes for current action/controller in ASP.NET MVC

asp.net-mvccustom-attributesauthorize-attribute

提问by DavGarcia

Checking out the sample code from http://lukesampson.com/post/471548689/entering-and-exiting-https-with-asp-net-mvcwritten for ASP.NET MVC2, I noticed they can check if a custom attribute is applied to the current action or controller by accessing filterContext.ActionDescriptorand filterContext.ActionDescriptor.ControllerDescriptorrespectively:

查看http://lukesampson.com/post/471548689/entering-and-exiting-https-with-asp-net-mvc为 ASP.NET MVC2 编写的示例代码,我注意到他们可以检查自定义属性是否是通过访问filterContext.ActionDescriptorfilterContext.ActionDescriptor.ControllerDescriptor分别应用于当前操作或控制器:

public class ExitHttpsIfNotRequiredAttribute : FilterAttribute, IAuthorizationFilter {
    public void OnAuthorization(AuthorizationContext filterContext) {
        // snip

        // abort if a [RequireHttps] attribute is applied to controller or action
        if(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;
        if(filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;

        // snip
    }
}

What would be the ASP.NET MVC 1 method of checking the action and controller for a custom attribute? In ASP.NET MVC 1 there is no filterContext.ActionDescriptorthat I can tell.

检查自定义属性的操作和控制器的 ASP.NET MVC 1 方法是什么?在 ASP.NET MVC 1 中filterContext.ActionDescriptor,我无法分辨。

采纳答案by DavGarcia

This seems to work... is there a better / more proper way in ASP.NET MVC 1?

这似乎有效……在 ASP.NET MVC 1 中有更好/更合适的方法吗?

if (filterContext.Controller.GetType().GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0)
    return;
string action = (string)filterContext.RouteData.Values["action"];
if (!string.IsNullOrEmpty(action) && filterContext.Controller.GetType().GetMethod(action).GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0)
    return;

回答by Sunday Ironfoot

Even better and more reliable* approach:

更好、更可靠*的方法:

filterContext.ActionDescriptor.GetCustomAttributes(
    typeof(RequireHttpsAttribute), true).Count> 0

Though this might be MVC 3.0+ only.

虽然这可能只是 MVC 3.0+。

回答by Ruben Bartelink

Goldplated edition, works on MVC5, probably 4/3:

镀金版,适用于 MVC5,大概 4/3:

filterContext.HasMarkerAttribute<RequireHttpsAttribute>()

Uses this set of helper extensions:

使用这组辅助扩展:

public static class MarkerAttributeExtensions
{
    public static bool HasMarkerAttribute<T>(this AuthorizationContext that) {
        return that.Controller.HasMarkerAttribute<T>()
            || that.ActionDescriptor.HasMarkerAttribute<T>();
    }

    public static bool HasMarkerAttribute<T>(this ActionExecutingContext that) {
        return that.Controller.HasMarkerAttribute<T>()
            || that.ActionDescriptor.HasMarkerAttribute<T>();
    }

    public static bool HasMarkerAttribute<T>(this ControllerBase that) {
        return that.GetType().HasMarkerAttribute<T>();
    }

    public static bool HasMarkerAttribute<T>(this Type that) {
        return that.IsDefined(typeof(T), false);
    }

    public static IEnumerable<T> GetCustomAttributes<T>(this Type that) {
        return that.GetCustomAttributes(typeof(T), false).Cast<T>();
    }

    public static bool HasMarkerAttribute<T>(this ActionDescriptor that) {
        return that.IsDefined(typeof(T), false);
    }

    public static IEnumerable<T> GetCustomAttributes<T>(this ActionDescriptor that) {
        return that.GetCustomAttributes(typeof(T), false).Cast<T>();
    }
}

回答by lisandro101

this worked for me in .NET Core 2.2:

这在 .NET Core 2.2 中对我有用:

var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;

if (controllerActionDescriptor != null)
{
    // Check if the attribute exists on the action method
    if (controllerActionDescriptor.MethodInfo?.GetCustomAttributes(inherit: true)?.Any(a => a.GetType().Equals(typeof(CustomAttribute))) ?? false)
        return true;

    // Check if the attribute exists on the controller
    if (controllerActionDescriptor.ControllerTypeInfo?.GetCustomAttributes(typeof(CustomAttribute), true)?.Any() ?? false)
        return true;
}

回答by Drew

I'm using MVC5 and had to use the following to check from within a class that inherits from ActionFilterAttribute and implements IAuthenticationFilter.

我正在使用 MVC5,并且必须使用以下内容从继承自 ActionFilterAttribute 并实现 IAuthenticationFilter 的类中进行检查。

If filterContext.ActionDescriptor.GetCustomAttributes(GetType(RequireHttpsAttribute), True).Any() OrElse filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(GetType(RequireHttpsAttribute), True).Any() Then
' .. the given attribute is present ..
End If

I couldn't get Ruben's solution to work for me but it was probably because I messed up in the conversion from C# to VB.

我无法让 Ruben 的解决方案对我有用,但这可能是因为我在从 C# 到 VB 的转换中搞砸了。