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

标签 asp.net-mvc custom-attributes authorize-attribute

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

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
    }
}

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

最佳答案

更好、更可靠的*方法:

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

尽管这可能仅限于 MVC 3.0+。

关于asp.net-mvc - 获取 ASP.NET MVC 中当前操作/ Controller 的自定义属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3569317/

相关文章:

c# - 何时在 MVC4 中使用包

.net - 使用属性的方法分析

asp.net-web-api - 如何使用 Microsoft.Owin.Security 自定义 System.Web.Http.AuthorizeAttribute?

asp.net-mvc - 将 MVC3 添加到现有 Webform 解决方案

asp.net-mvc - MVC : Access display name attribute in the controller

javascript - .remove 不是函数

c# - 反射使HashCode不稳定

asp.net-mvc - 修剪除具有 NoTrim 属性的输入字段之外的所有输入字段

asp.net-mvc - MVC3 中的 OutputCache 和 Authorize 过滤器

c# - 在 asp.net mvc5 中使用自定义登录进行表单例份验证